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.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.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.Reporting
Provides reporting classes for populating documents designed in Microsoft Word with data from various data sources.
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.Tables
Contains classes to work with tables, rows, cells and their formatting.

We guarantee a prompt response to any inquiry!

© 2003-2014 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.
ComHelper | Provides methods for COM clients to load a document into Aspose.Words.
Comment | Represents a container for text of a comment.
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.
CompositeNode | Base class for nodes that can contain other nodes.
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.
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 or endnote numbering options for a document or section.
HeaderFooter | Represents a container for the header or footer text of a section.
HeaderFooterCollection | Provides typed access to HeaderFooter nodes of a Section.
Hyphenation | Provides methods for working with hyphenation dictionaries. These dictionaries prescribe where words of a specific language can be hyphenated.
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.
InterruptionToken | This class provides members to manually interrupt Aspose.Words during long running tasks.
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.
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.
Range | Represents a contiguous area in a document.
ReplacingArgs | Provides data for a custom replace operation.
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.
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.
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.
UnsupportedFileFormatException | Thrown during document load, when the document format is not recognized or not supported by Aspose.Words.
VariableCollection | A collection of document variables.
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.
IReplacingCallback | Implement this interface if you want to have your own custom method called during a find and replace operation.
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.
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.
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.
FootnoteLocation | Defines the footnote or endnote position.
FootnoteNumberingRule | Determines when automatic footnote or endnote numbering restarts.
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.
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.
MsWordVersion | Allows Aspose.Wods to mimic MS Word version-specific application behavior.
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.
ReplaceAction | Allows the user to specify what happens to the current match during a replace operation.
RevisionType | Specifies the type of change being tracked in Revision.
SaveFormat | Indicates the format in which the document is saved.
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.
TextEffect | Animation effect for text runs.
TextOrientation | Specifies orientation of text in a table cell or a text frame.
TextureIndex | Specifies shading texture.
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:2014-06-03 11:20:58,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

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.
IsInsertRevision (inherited from Inline) | Returns true if this object was 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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.");
        }
    }
}
[Visual Basic]

' Open a document.
Dim doc As New Document(MyDir & "Section.BodyNodeType.doc")

' Get the first section in the document.
Dim section As Section = doc.FirstSection

' A Section is a composite node and therefore can contain child nodes.
' Section can contain only Body and HeaderFooter nodes.
For Each node As Node In section
    ' Every node has the NodeType property.
    Select Case node.NodeType
        Case NodeType.Body
            ' If the node type is Body, we can cast the node to the Body class.
            Dim body As Body = CType(node, Body)

            ' Write the content of the main story of the section to the console.
            Console.WriteLine("*** Body ***")
            Console.WriteLine(body.GetText())
            Exit Select
        Case NodeType.HeaderFooter
            ' If the node type is HeaderFooter, we can cast the node to the HeaderFooter class.
            Dim headerFooter As HeaderFooter = CType(node, HeaderFooter)

            ' Write the content of the header footer to the console.
            Console.WriteLine("*** HeaderFooter ***")
            Console.WriteLine(headerFooter.HeaderFooterType)
            Console.WriteLine(headerFooter.GetText())
            Exit Select
        Case Else
            ' Other types of nodes never occur inside a Section node.
            Throw New Exception("Unexpected node type in a section.")
    End Select
Next node

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.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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)
{
    // 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());
[Visual Basic]

' Open a document.
Dim doc As 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.
For Each section As Section In doc.Sections
    ' Each section has a Body node that contains main story (main text) of the section.
    Dim body As 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()
Next section

' 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.";
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmark.doc")

' Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Dim bookmark As Bookmark = doc.Range.Bookmarks("MyBookmark")

' Get the name and text of the bookmark.
Dim name As String = bookmark.Name
Dim text As String = 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;}

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;}

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 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.";
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmark.doc")

' Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Dim bookmark As Bookmark = doc.Range.Bookmarks("MyBookmark")

' Get the name and text of the bookmark.
Dim name As String = bookmark.Name
Dim text As String = 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.";
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmark.doc")

' Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Dim bookmark As Bookmark = doc.Range.Bookmarks("MyBookmark")

' Get the name and text of the bookmark.
Dim name As String = bookmark.Name
Dim text As String = 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();
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmark.doc")

' Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Dim bookmark As 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
[C#]
public class BookmarkCollection : 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"];
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmarks.doc")

' By index.
Dim bookmark1 As Bookmark = doc.Range.Bookmarks(0)

' By name.
Dim bookmark2 As Bookmark = 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;
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmark.doc")

Dim count As Integer = 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"];
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmarks.doc")

' By index.
Dim bookmark1 As Bookmark = doc.Range.Bookmarks(0)

' By name.
Dim bookmark2 As Bookmark = 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"];
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmarks.doc")

' By index.
Dim bookmark1 As Bookmark = doc.Range.Bookmarks(0)

' By name.
Dim bookmark2 As Bookmark = 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();
[Visual Basic]

Dim doc As 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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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);
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmarks.doc")
' Remove a particular bookmark from the document.
Dim bookmark As 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);
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmarks.doc")
' Remove a particular bookmark from the document.
Dim bookmark As 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);
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmarks.doc")
' Remove a particular bookmark from the document.
Dim bookmark As 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.

Note Currently bookmarks are supported only at the inline-level, that is inside Paragraph, but bookmark start and bookmark end can be in different paragraphs.

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 the name of the bookmark.
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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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 the name of the bookmark.
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 the name of the bookmark.

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

Remarks

Cannot be null.

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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.

Note Currently bookmarks are supported only at the inline-level, that is inside Paragraph, but bookmark start and bookmark end can be in different paragraphs.

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 | Get 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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 | Get 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;}

See Also

BookmarkStart Class | Aspose.Words Namespace


Name Property

Aspose.Words

BookmarkStart.Name Property

Get the bookmark name.

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

Remarks

Cannot be null.

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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.

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.Border

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

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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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 = System.Drawing.Color.Red;
topBorder.LineStyle = LineStyle.DashSmallGap;
topBorder.LineWidth = 4;

builder.Writeln("Hello World!");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim topBorder As Border = builder.ParagraphFormat.Borders(BorderType.Top)
topBorder.Color = System.Drawing.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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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 = System.Drawing.Color.Blue;
border.DistanceFromText = 0;

doc.Save(MyDir + "PageSetup.PageBorderTop Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim ps As PageSetup = doc.Sections(0).PageSetup
ps.BorderAlwaysInFront = False
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage

Dim border As Border = ps.Borders(BorderType.Top)
border.LineStyle = LineStyle.Single
border.LineWidth = 30
border.Color = System.Drawing.Color.Blue
border.DistanceFromText = 0

doc.Save(MyDir & "PageSetup.PageBorderTop Out.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;}

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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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 = System.Drawing.Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(MyDir + "PageSetup.PageBorders Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim ps As PageSetup = doc.Sections(0).PageSetup

ps.Borders.LineStyle = LineStyle.DoubleWave
ps.Borders.LineWidth = 2
ps.Borders.Color = System.Drawing.Color.Green
ps.Borders.DistanceFromText = 24
ps.Borders.Shadow = True

doc.Save(MyDir & "PageSetup.PageBorders Out.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.

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
);

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();

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]
Public Class BorderCollection
Implements IEnumerable
[C#]
public class BorderCollection : 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 = System.Drawing.Color.Red;
topBorder.LineStyle = LineStyle.DashSmallGap;
topBorder.LineWidth = 4;

builder.Writeln("Hello World!");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim topBorder As Border = builder.ParagraphFormat.Borders(BorderType.Top)
topBorder.Color = System.Drawing.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(MyDir + "Table.SetBordersAndShading Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir & "Table.SetBordersAndShading Out.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 = System.Drawing.Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(MyDir + "PageSetup.PageBorders Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim ps As PageSetup = doc.Sections(0).PageSetup

ps.Borders.LineStyle = LineStyle.DoubleWave
ps.Borders.LineWidth = 2
ps.Borders.Color = System.Drawing.Color.Green
ps.Borders.DistanceFromText = 24
ps.Borders.Shadow = True

doc.Save(MyDir & "PageSetup.PageBorders Out.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;}

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 = System.Drawing.Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(MyDir + "PageSetup.PageBorders Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim ps As PageSetup = doc.Sections(0).PageSetup

ps.Borders.LineStyle = LineStyle.DoubleWave
ps.Borders.LineWidth = 2
ps.Borders.Color = System.Drawing.Color.Green
ps.Borders.DistanceFromText = 24
ps.Borders.Shadow = True

doc.Save(MyDir & "PageSetup.PageBorders Out.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;}

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 = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;

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

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph borders
Dim borders As BorderCollection = 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
Dim shading As Shading = builder.ParagraphFormat.Shading
shading.Texture = TextureIndex.TextureDiagonalCross
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral
shading.ForegroundPatternColor = System.Drawing.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.

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(MyDir + "Table.SetBordersAndShading Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir & "Table.SetBordersAndShading Out.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 = System.Drawing.Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(MyDir + "PageSetup.PageBorders Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim ps As PageSetup = doc.Sections(0).PageSetup

ps.Borders.LineStyle = LineStyle.DoubleWave
ps.Borders.LineWidth = 2
ps.Borders.Color = System.Drawing.Color.Green
ps.Borders.DistanceFromText = 24
ps.Borders.Shadow = True

doc.Save(MyDir & "PageSetup.PageBorders Out.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 = System.Drawing.Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(MyDir + "PageSetup.PageBorders Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim ps As PageSetup = doc.Sections(0).PageSetup

ps.Borders.LineStyle = LineStyle.DoubleWave
ps.Borders.LineWidth = 2
ps.Borders.Color = System.Drawing.Color.Green
ps.Borders.DistanceFromText = 24
ps.Borders.Shadow = True

doc.Save(MyDir & "PageSetup.PageBorders Out.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(MyDir + "Table.SetBordersAndShading Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir & "Table.SetBordersAndShading Out.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 = System.Drawing.Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(MyDir + "PageSetup.PageBorders Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim ps As PageSetup = doc.Sections(0).PageSetup

ps.Borders.LineStyle = LineStyle.DoubleWave
ps.Borders.LineWidth = 2
ps.Borders.Color = System.Drawing.Color.Green
ps.Borders.DistanceFromText = 24
ps.Borders.Shadow = True

doc.Save(MyDir & "PageSetup.PageBorders Out.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(MyDir + "Table.SetBordersAndShading Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir & "Table.SetBordersAndShading Out.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;}

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();

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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 = System.Drawing.Color.Red;
topBorder.LineStyle = LineStyle.DashSmallGap;
topBorder.LineWidth = 4;

builder.Writeln("Hello World!");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim topBorder As Border = builder.ParagraphFormat.Borders(BorderType.Top)
topBorder.Color = System.Drawing.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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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(MyDir + "DocumentBuilder.HeadersAndFooters Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.HeadersAndFooters Out.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();
[Visual Basic]

' Use a blank document
Dim doc As New Document()

' Create a document builder to insert content with into document.
Dim builder As 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]
Public Class BuildVersionInfo
[C#]
public class BuildVersionInfo

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;}

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.

See Also

BuildVersionInfo 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)

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();

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.

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)

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]
Public Class Comment
Inherits InlineStory
[C#]
public 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."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim comment As 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."))

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

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.
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.
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.
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.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim comment As 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

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.
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.
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.
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


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

Extracts the author name, date&time and text of all comments in the document.

[C#]

static ArrayList ExtractComments(Document doc)
{
    ArrayList collectedComments = new ArrayList();
    // Collect all comments in the document
    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);
    // Look through all comments and gather information about them.
    foreach (Comment comment in comments)
    {
        collectedComments.Add(comment.Author + " " + comment.DateTime + " " + comment.ToString(SaveFormat.Text));
    }
    return collectedComments;
}
[Visual Basic]

Private Shared Function ExtractComments(ByVal doc As Document) As ArrayList
    Dim collectedComments As New ArrayList()
    ' Collect all comments in the document
    Dim comments As NodeCollection = doc.GetChildNodes(NodeType.Comment, True)
    ' Look through all comments and gather information about them.
    For Each comment As Comment In comments
        collectedComments.Add(comment.Author & " " & comment.DateTime & " " & comment.ToString(SaveFormat.Text))
    Next comment
    Return collectedComments
End Function

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

Extracts the author name, date&time and text of all comments in the document.

[C#]

static ArrayList ExtractComments(Document doc)
{
    ArrayList collectedComments = new ArrayList();
    // Collect all comments in the document
    NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);
    // Look through all comments and gather information about them.
    foreach (Comment comment in comments)
    {
        collectedComments.Add(comment.Author + " " + comment.DateTime + " " + comment.ToString(SaveFormat.Text));
    }
    return collectedComments;
}
[Visual Basic]

Private Shared Function ExtractComments(ByVal doc As Document) As ArrayList
    Dim collectedComments As New ArrayList()
    ' Collect all comments in the document
    Dim comments As NodeCollection = doc.GetChildNodes(NodeType.Comment, True)
    ' Look through all comments and gather information about them.
    For Each comment As Comment In comments
        collectedComments.Add(comment.Author & " " & comment.DateTime & " " & comment.ToString(SaveFormat.Text))
    Next comment
    Return collectedComments
End Function

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.

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.

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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


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;}

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.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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.

See Also

Comment 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]
Public Class CommentRangeEnd
Inherits Node
[C#]
public 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.

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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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;}

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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]
Public Class CommentRangeStart
Inherits Node
[C#]
public 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.

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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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;}

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

See Also

CommentRangeStart Class | 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, IXPathNavigable
[C#]
public abstract class CompositeNode : Node, 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);
[Visual Basic]

Dim paragraph As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

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) | Creates a duplicate of the 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 | Overloaded. Returns a 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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);
    }
}
[Visual Basic]

Dim children As NodeCollection = paragraph.ChildNodes
For Each child As Node In children
    ' Paragraph may contain children of various types such as runs, shapes and so on.
    If child.NodeType.Equals(NodeType.Run) Then
        ' Say we found the node that we want, do something useful.
        Dim run As Run = CType(child, Run)
        Console.WriteLine(run.Text)
    End If
Next child

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;}

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));
}
[Visual Basic]

' Get the section that we want to work on.
Dim section As Section = doc.Sections(0)
Dim body As Body = section.Body

' Loop starting from the first child until we reach null.
Dim node As Node = body.FirstChild
Do While node IsNot Nothing
    ' Output the types of the nodes that we come across.
    Console.WriteLine(Node.NodeTypeToString(node.NodeType))
    node = node.NextSibling
Loop
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);
    }
}
[Visual Basic]

Public Sub RecurseAllNodes()
    ' Open a document.
    Dim doc As New Document(MyDir & "Node.RecurseAllNodes.doc")

    ' Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc)
End Sub

''' <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 Sub TraverseAllNodes(ByVal parentNode As CompositeNode)
    ' This is the most efficient way to loop through immediate children of a node.
    Dim childNode As Node = parentNode.FirstChild
    Do While childNode IsNot Nothing
        ' Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType))

        ' Recurse into the node if it is a composite node.
        If childNode.IsComposite Then
            TraverseAllNodes(CType(childNode, CompositeNode))
        End If
        childNode = childNode.NextSibling
    Loop
End Sub

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#]

public void InsertDocumentAtMailMerge()
{
    // 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 string[] { MyDir + "InsertDocument2.doc" });

    mainDoc.Save(MyDir + "InsertDocumentAtMailMerge Out.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 e)
    {
        if (e.DocumentFieldName == "Document_1")
        {
            // Use document builder to navigate to the merge field with the specified name.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);

            // The name of the document to load and insert is stored in the field value.
            Document subDoc = new Document((string)e.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.
            e.Text = null;
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do nothing.
    }
}
[Visual Basic]

Public Sub InsertDocumentAtMailMerge()
    ' Open the main document.
    Dim mainDoc As 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 String() { MyDir & "InsertDocument2.doc" })

    mainDoc.Save(MyDir & "InsertDocumentAtMailMerge Out.doc")
End Sub

Private Class InsertDocumentAtMailMergeHandler
    Implements 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>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        If e.DocumentFieldName = "Document_1" Then
            ' Use document builder to navigate to the merge field with the specified name.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)

            ' The name of the document to load and insert is stored in the field value.
            Dim subDoc As New Document(CStr(e.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 (Not builder.CurrentParagraph.HasChildNodes) Then
                builder.CurrentParagraph.Remove()
            End If

            ' Indicate to the mail merge engine that we have inserted what we wanted.
            e.Text = Nothing
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

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);
    }
}
[Visual Basic]

Public Sub RecurseAllNodes()
    ' Open a document.
    Dim doc As New Document(MyDir & "Node.RecurseAllNodes.doc")

    ' Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc)
End Sub

''' <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 Sub TraverseAllNodes(ByVal parentNode As CompositeNode)
    ' This is the most efficient way to loop through immediate children of a node.
    Dim childNode As Node = parentNode.FirstChild
    Do While childNode IsNot Nothing
        ' Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType))

        ' Recurse into the node if it is a composite node.
        If childNode.IsComposite Then
            TraverseAllNodes(CType(childNode, CompositeNode))
        End If
        childNode = childNode.NextSibling
    Loop
End Sub

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);
[Visual Basic]

' 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.
Dim lastSection As Node = 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.
Dim sectionBeforeLast As Node = lastSection.PreviousSibling

If sectionBeforeLast IsNot Nothing Then
    doc.RemoveChild(sectionBeforeLast)
End If

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) | Creates a duplicate of the 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 | Overloaded. Returns a 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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.

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.

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);
[Visual Basic]

Dim paragraph As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), 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;
    }
}
[Visual Basic]

' Let's pick a document we know has some fields in.
Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

' Let's say we want to check if the Run below is inside a field.
Dim run As Run = CType(doc.GetChild(NodeType.Run, 5, True), Run)

' 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.
Dim resultList As NodeList = doc.SelectNodes("//FieldStart/following-sibling::node()[following-sibling::FieldEnd]")

' Check if the specified run is one of the nodes that are inside the field.
For Each node As Node In resultList
    If node Is run Then
        Console.WriteLine("The node is found inside a field")
        Exit For
    End If
Next node

See Also

CompositeNode Class | Aspose.Words Namespace


GetChildNodes Method

Aspose.Words

CompositeNode.GetChildNodes Method

Returns a collection of child nodes that match the specified type.

Overload List

Returns a live collection of child nodes that match the specified type.

public NodeCollection GetChildNodes(NodeType,bool);

Obsolete. Returns a collection of child nodes that match the specified type.

public NodeCollection GetChildNodes(NodeType,bool,bool);

See Also

CompositeNode Class | Aspose.Words Namespace


CompositeNode.GetChildNodes Method (NodeType, Boolean)

Returns a live collection of child nodes that match the specified type.

[Visual Basic]
Overloads 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(MyDir + "Document.TableOfContentsRemoveTOC Out.doc");
[Visual Basic]

' Open a document which contains a TOC.
Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

' Remove the first TOC from the document.
Dim tocField As Field = doc.Range.Fields(0)
tocField.Remove()

' Save the output.
doc.Save(MyDir & "Document.TableOfContentsRemoveTOC Out.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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

See Also

CompositeNode Class | Aspose.Words Namespace | CompositeNode.GetChildNodes Overload List


CompositeNode.GetChildNodes Method (NodeType, Boolean, Boolean)

NOTE: This method is now obsolete.

Use GetChildNodes(NodeType, bool).

Returns a collection of child nodes that match the specified type.

[Visual Basic]
Overloads Public Function GetChildNodes( _
ByVal nodeType As NodeType, _
ByVal isDeep As Boolean, _
ByVal isLive As Boolean _
) As NodeCollection
[C#]
public NodeCollection GetChildNodes(
NodeType nodeType,
bool isDeep,
bool isLive
);

Remarks

This method is obsolete. isLive is not used anymore. Please use GetChildNodes instead.

See Also

CompositeNode Class | Aspose.Words Namespace | CompositeNode.GetChildNodes Overload List


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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.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);
    }
}
[Visual Basic]

Dim children As NodeCollection = paragraph.ChildNodes
For Each child As Node In children
    ' Paragraph may contain children of various types such as runs, shapes and so on.
    If child.NodeType.Equals(NodeType.Run) Then
        ' Say we found the node that we want, do something useful.
        Dim run As Run = CType(child, Run)
        Console.WriteLine(run.Text)
    End If
Next child

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)
{
    if (para.ListFormat.IsListItem)
    {
        Console.WriteLine(string.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId));
        Console.WriteLine(para.GetText());
    }
}
[Visual Basic]

Dim paras As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
For Each para As Paragraph In paras
    If para.ListFormat.IsListItem Then
        Console.WriteLine(String.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId))
        Console.WriteLine(para.GetText())
    End If
Next para
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));
[Visual Basic]

Dim doc As New Document()

' Enter a dummy field into the document.
Dim builder As 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 row in a table.

[C#]

int rowIndex = table.IndexOf(row);
[Visual Basic]

Dim rowIndex As Integer = table.IndexOf(row)
Retrieves the index of a cell in a row.
[C#]

int cellIndex = row.IndexOf(cell);
[Visual Basic]

Dim cellIndex As Integer = row.IndexOf(cell)
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);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

' Get the body of the first section in the document.
Dim body As Body = doc.FirstSection.Body
' Retrieve the index of the last paragraph in the body.
Dim index As Integer = 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)
{
    // 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(MyDir + "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(MyDir + "Shape.ReplaceTextboxesWithImages Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Shape.ReplaceTextboxesWithImages.doc")

' This gets a live collection of all shape nodes in the document.
Dim shapeCollection As NodeCollection = 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.
Dim shapes() As Node = shapeCollection.ToArray()

For Each shape As Shape In shapes
    ' Filter out all shapes that we don't need.
    If shape.ShapeType.Equals(ShapeType.TextBox) Then
        ' Create a new shape that will replace the existing shape.
        Dim image As New Shape(doc, ShapeType.Image)

        ' Load the image into the new shape.
        image.ImageData.SetImage(MyDir & "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()
    End If
Next shape

doc.Save(MyDir & "Shape.ReplaceTextboxesWithImages Out.doc")

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.

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 manually prepend the content from one document to the beginning of another document.

[C#]

public static void PrependDocumentMain()
{
    Document dstDoc = new Document(gDataDir + "TestFile.Destination.doc");
    Document srcDoc = new Document(gDataDir + "TestFile.Source.doc");

    // Append the source document to the destination document. This causes the result to have line spacing problems.
    dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);

    // Instead prepend the content of the destination document to the start of the source document.
    // This results in the same joined document but with no line spacing issues.
    PrependDocument(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting);
}

/// <summary>
/// A modified version of the AppendDocument method which prepends the content of one document to the start
/// of another.
/// </summary>
/// <param name="dstDoc">The destination document where to prepend the source document to.</param>
/// <param name="srcDoc">The source document.</param>
public static void PrependDocument(Document dstDoc, Document srcDoc, ImportFormatMode mode)
{
    // Loop through all sections in the source document.
    // Section nodes are immediate children of the Document node so we can just enumerate the Document.
    ArrayList sections = new ArrayList(srcDoc.Sections.ToArray());

    // Reverse the order of the sections so they are prepended to start of the destination document in the correct order.
    sections.Reverse();

    foreach (Section srcSection in sections)
    {
        // Import the nodes from the source document.
        Node dstSection = dstDoc.ImportNode(srcSection, true, mode);

        // Now the new section node can be prepended to the destination document.
        // Note how PrependChild is used instead of AppendChild. This is the only line changed compared
        // to the original method.
        dstDoc.PrependChild(dstSection);
    }
}
[Visual Basic]

Public Shared Sub PrependDocumentMain()
    Dim dstDoc As New Document(gDataDir & "TestFile.Destination.doc")
    Dim srcDoc As New Document(gDataDir & "TestFile.Source.doc")

    ' Append the source document to the destination document. This causes the result to have line spacing problems.
    dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting)

    ' Instead prepend the content of the destination document to the start of the source document.
    ' This results in the same joined document but with no line spacing issues.
    PrependDocument(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting)
End Sub

''' <summary>
''' A modified version of the AppendDocument method which prepends the content of one document to the start
''' of another.
''' </summary>
''' <param name="dstDoc">The destination document where to prepend the source document to.</param>
''' <param name="srcDoc">The source document.</param>
Public Shared Sub PrependDocument(ByVal dstDoc As Document, ByVal srcDoc As Document, ByVal mode As ImportFormatMode)
    ' Loop through all sections in the source document.
    ' Section nodes are immediate children of the Document node so we can just enumerate the Document.
    Dim sections As New ArrayList(srcDoc.Sections.ToArray())

    ' Reverse the order of the sections so they are prepended to start of the destination document in the correct order.
    sections.Reverse()

    For Each srcSection As Section In sections
        ' Import the nodes from the source document.
        Dim dstSection As Node = dstDoc.ImportNode(srcSection, True, mode)

        ' Now the new section node can be prepended to the destination document.
        ' Note how PrependChild is used instead of AppendChild. This is the only line changed compared
        ' to the original method.
        dstDoc.PrependChild(dstSection)
    Next srcSection
End Sub

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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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);
[Visual Basic]

' 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.
Dim lastSection As Node = 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.
Dim sectionBeforeLast As Node = lastSection.PreviousSibling

If sectionBeforeLast IsNot Nothing Then
    doc.RemoveChild(sectionBeforeLast)
End If

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();
[Visual Basic]

Dim doc As 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();
[Visual Basic]

Dim doc As 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");
[Visual Basic]

Dim doc As 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.
Dim nodeList As 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.
Dim node As 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;
    }
}
[Visual Basic]

' Let's pick a document we know has some fields in.
Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

' Let's say we want to check if the Run below is inside a field.
Dim run As Run = CType(doc.GetChild(NodeType.Run, 5, True), Run)

' 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.
Dim resultList As NodeList = doc.SelectNodes("//FieldStart/following-sibling::node()[following-sibling::FieldEnd]")

' Check if the specified run is one of the nodes that are inside the field.
For Each node As Node In resultList
    If node Is run Then
        Console.WriteLine("The node is found inside a field")
        Exit For
    End If
Next node

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");
[Visual Basic]

Dim doc As 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.
Dim nodeList As 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.
Dim node As Node = doc.SelectSingleNode("//Body/Paragraph")

See Also

CompositeNode Class | 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.
doc.Save(Response, "MailMerge.ExecuteArray Out.doc", ContentDisposition.Inline, null);
[Visual Basic]

' Open an existing document.
Dim doc As 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.
doc.Save(Response, "MailMerge.ExecuteArray Out.doc", ContentDisposition.Inline, Nothing)

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]
Public Class ControlChar
[C#]
public 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);
[Visual Basic]

' 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;

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 = ;

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;

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 = ;

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);
[Visual Basic]

' 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);
[Visual Basic]

' 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 =  ;

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 = ;

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 = ;

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 = ;

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;

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;

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 = ;

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;

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 = ;

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.

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;

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 = ;

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.

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

Removes all page breaks from the document.

[C#]

private static void RemovePageBreaks(Document doc)
{
    // Retrieve all paragraphs in the document.
    NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);

    // Iterate through all paragraphs
    foreach (Paragraph para in paragraphs)
    {
        // If the paragraph has a page break before set then clear it.
        if (para.ParagraphFormat.PageBreakBefore)
            para.ParagraphFormat.PageBreakBefore = false;

        // Check all runs in the paragraph for page breaks and remove them.
        foreach (Run run in para.Runs)
        {
            if (run.Text.Contains(ControlChar.PageBreak))
                run.Text = run.Text.Replace(ControlChar.PageBreak, string.Empty);
        }

    }

}
[Visual Basic]

Private Shared Sub RemovePageBreaks(ByVal doc As Document)
    ' Retrieve all paragraphs in the document.
    Dim paragraphs As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)

    ' Iterate through all paragraphs
    For Each para As Paragraph In paragraphs
        ' If the paragraph has a page break before set then clear it.
        If para.ParagraphFormat.PageBreakBefore Then
            para.ParagraphFormat.PageBreakBefore = False
        End If

        ' Check all runs in the paragraph for page breaks and remove them.
        For Each run As Run In para.Runs
            If run.Text.Contains(ControlChar.PageBreak) Then
                run.Text = run.Text.Replace(ControlChar.PageBreak, String.Empty)
            End If
        Next run

    Next para

End Sub

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 = ;

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;

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 = ;

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;

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 = ;

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 = ;

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!");
[Visual Basic]

Dim builder As 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!");
[Visual Basic]

Dim builder As 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]
Public Class ConvertUtil
[C#]
public 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);
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim pageSetup As 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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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.

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.

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.

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.

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.

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.

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.

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.Signed.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.ToString());
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.Certificate.SubjectName.ToString());
    Console.WriteLine("Issuer name: " + signature.Certificate.IssuerName.Name);
    Console.WriteLine();
}
[Visual Basic]

' Load the document which contains signature.
Dim doc As New Document(MyDir & "Document.Signed.docx")

For Each signature As DigitalSignature 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.ToString())
    Console.WriteLine("Time of signing: " & signature.SignTime)
    Console.WriteLine("Subject name: " & signature.Certificate.SubjectName.ToString())
    Console.WriteLine("Issuer name: " & signature.Certificate.IssuerName.Name)
    Console.WriteLine()
Next signature

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 | Returns the certificate object that was used to sign the document.
Comments | Gets the signing purpose comment.
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.

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 | Returns the certificate object that was used to sign the document.
Comments | Gets the signing purpose comment.
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.

See Also

DigitalSignature Class | Aspose.Words Namespace


Certificate Property

Aspose.Words

DigitalSignature.Certificate Property

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.Signed.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.ToString());
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.Certificate.SubjectName.ToString());
    Console.WriteLine("Issuer name: " + signature.Certificate.IssuerName.Name);
    Console.WriteLine();
}
[Visual Basic]

' Load the document which contains signature.
Dim doc As New Document(MyDir & "Document.Signed.docx")

For Each signature As DigitalSignature 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.ToString())
    Console.WriteLine("Time of signing: " & signature.SignTime)
    Console.WriteLine("Subject name: " & signature.Certificate.SubjectName.ToString())
    Console.WriteLine("Issuer name: " & signature.Certificate.IssuerName.Name)
    Console.WriteLine()
Next signature

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.Signed.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.ToString());
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.Certificate.SubjectName.ToString());
    Console.WriteLine("Issuer name: " + signature.Certificate.IssuerName.Name);
    Console.WriteLine();
}
[Visual Basic]

' Load the document which contains signature.
Dim doc As New Document(MyDir & "Document.Signed.docx")

For Each signature As DigitalSignature 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.ToString())
    Console.WriteLine("Time of signing: " & signature.SignTime)
    Console.WriteLine("Subject name: " & signature.Certificate.SubjectName.ToString())
    Console.WriteLine("Issuer name: " & signature.Certificate.IssuerName.Name)
    Console.WriteLine()
Next signature

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.Signed.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.ToString());
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.Certificate.SubjectName.ToString());
    Console.WriteLine("Issuer name: " + signature.Certificate.IssuerName.Name);
    Console.WriteLine();
}
[Visual Basic]

' Load the document which contains signature.
Dim doc As New Document(MyDir & "Document.Signed.docx")

For Each signature As DigitalSignature 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.ToString())
    Console.WriteLine("Time of signing: " & signature.SignTime)
    Console.WriteLine("Subject name: " & signature.Certificate.SubjectName.ToString())
    Console.WriteLine("Issuer name: " & signature.Certificate.IssuerName.Name)
    Console.WriteLine()
Next signature

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.Signed.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.ToString());
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.Certificate.SubjectName.ToString());
    Console.WriteLine("Issuer name: " + signature.Certificate.IssuerName.Name);
    Console.WriteLine();
}
[Visual Basic]

' Load the document which contains signature.
Dim doc As New Document(MyDir & "Document.Signed.docx")

For Each signature As DigitalSignature 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.ToString())
    Console.WriteLine("Time of signing: " & signature.SignTime)
    Console.WriteLine("Subject name: " & signature.Certificate.SubjectName.ToString())
    Console.WriteLine("Issuer name: " & signature.Certificate.IssuerName.Name)
    Console.WriteLine()
Next signature

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.Signed.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.ToString());
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.Certificate.SubjectName.ToString());
    Console.WriteLine("Issuer name: " + signature.Certificate.IssuerName.Name);
    Console.WriteLine();
}
[Visual Basic]

' Load the document which contains signature.
Dim doc As New Document(MyDir & "Document.Signed.docx")

For Each signature As DigitalSignature 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.ToString())
    Console.WriteLine("Time of signing: " & signature.SignTime)
    Console.WriteLine("Subject name: " & signature.Certificate.SubjectName.ToString())
    Console.WriteLine("Issuer name: " & signature.Certificate.IssuerName.Name)
    Console.WriteLine()
Next signature

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
[C#]
public class DigitalSignatureCollection : IEnumerable

Remarks

DigitalSignatures

Example

Shows how to validate all signatures in a document.

[C#]

// Load the signed document.
Document doc = new Document(MyDir + "Document.Signed.docx");

if (doc.DigitalSignatures.IsValid)
    Console.WriteLine("Signatures belonging to this document are valid");
else
    Console.WriteLine("Signatures belonging to this document are NOT valid");
[Visual Basic]

' Load the signed document.
Dim doc As New Document(MyDir & "Document.Signed.docx")

If doc.DigitalSignatures.IsValid Then
    Console.WriteLine("Signatures belonging to this document are valid")
Else
    Console.WriteLine("Signatures belonging to this document are NOT valid")
End If

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;}

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.Signed.docx");

if (doc.DigitalSignatures.IsValid)
    Console.WriteLine("Signatures belonging to this document are valid");
else
    Console.WriteLine("Signatures belonging to this document are NOT valid");
[Visual Basic]

' Load the signed document.
Dim doc As New Document(MyDir & "Document.Signed.docx")

If doc.DigitalSignatures.IsValid Then
    Console.WriteLine("Signatures belonging to this document are valid")
Else
    Console.WriteLine("Signatures belonging to this document are NOT valid")
End If

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.

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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

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]
Public Class DigitalSignatureUtil
[C#]
public 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.

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 digital signature and writes signed document to destination file. Document should be either Doc or Docx.

Public Instance Constructors

DigitalSignatureUtil Constructor Initializes a new instance of the DigitalSignatureUtil class.

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace


DigitalSignatureUtil Constructor

Initializes a new instance of the DigitalSignatureUtil class.

[Visual Basic]
Public Sub New()
[C#]
public DigitalSignatureUtil();

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 digital signature and writes signed document to destination file. Document should be either Doc or Docx.

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace


LoadSignatures Method

Aspose.Words

DigitalSignatureUtil.LoadSignatures Method

Loads digital signatures from document.

Overload List

Loads digital signatures from document.

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.

[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 the document.

Return Value

Collection of digital signatures. Returns empty collection if file is not signed.

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.

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
);

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
);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.RemoveAllSignatures Overload List


Sign Method

Aspose.Words

DigitalSignatureUtil.Sign Method

Signs source document using given 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 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,X509Certificate2,string,DateTime);

Signs source document using given digital signature and writes signed document to destination file. Document should be either Doc or Docx.

public static void Sign(string,string,X509Certificate2,string,DateTime);

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace


DigitalSignatureUtil.Sign Method (Stream, Stream, X509Certificate2, String, DateTime)

Signs source document using given 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 certificate As X509Certificate2, _
ByVal comments As String, _
ByVal signTime As Date _
)
[C#]
public static void Sign(
Stream srcStream,
Stream dstStream,
X509Certificate2 certificate,
string comments,
DateTime signTime
);

Parameters

srcStream
The stream which contains the document to sign.
dstStream
The stream that signed document will be written to.
certificate
Certificate object used to sign file. The certificate MUST contain private keys.
comments
The reason for signing.
signTime
The date of signing.

See Also

DigitalSignatureUtil Class | Aspose.Words Namespace | DigitalSignatureUtil.Sign Overload List


DigitalSignatureUtil.Sign Method (String, String, X509Certificate2, String, DateTime)

Signs source document using given 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 certificate As X509Certificate2, _
ByVal comments As String, _
ByVal signTime As Date _
)
[C#]
public static void Sign(
string srcFileName,
string dstFileName,
X509Certificate2 certificate,
string comments,
DateTime signTime
);

Parameters

srcFileName
The file name of the document to sign.
dstFileName
The file name of the signed document output.
certificate
Certificate object used to sign file. The certificate MUST contain private keys.
comments
The reason for signing.
signTime
The date of signing.

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(MyDir + "Document.Doc2PdfSave Out.pdf");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

doc.Save(MyDir & "Document.Doc2PdfSave Out.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(MyDir + "MailMerge.ExecuteDataTable Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "MailMerge.ExecuteDataTable.doc")

' This example creates a table, but you would normally load table from a database.
Dim table As 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(MyDir & "MailMerge.ExecuteDataTable Out.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 document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).
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.
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.
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.
ResourceLoadingCallback (inherited from DocumentBase) | Allows to control how external resources are loaded.
Revisions | Gets a 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.
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.
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.
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 | Appends the specified document to the end of this document.
Clone | Overloaded. Performs a deep copy of the Document.
Clone (inherited from Node) | Overloaded. Creates a duplicate of the node.
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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
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.
RemoveUnusedResources | Removes unused styles and lists from the document.
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.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.
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 | 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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Create a new run of text.
Dim run As New Run(doc, "Hello")

' Specify character formatting for the run of text.
Dim f As Aspose.Words.Font = 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");
[Visual Basic]

' Open a document. The file is opened read only and only for the duration of the constructor.
Dim doc As 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"));
[Visual Basic]

Dim doc As 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);
[Visual Basic]

Dim loadOptions As New LoadOptions()
loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html
Dim doc As 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.
Stream stream = File.OpenRead(MyDir + "Document.doc");

// Load the entire document into memory.
Document doc = new Document(stream);

// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();

// ... do something with the document
[Visual Basic]

' Open the stream. Read only access is enough for Aspose.Words to load a document.
Dim stream As Stream = File.OpenRead(MyDir & "Document.doc")

' Load the entire document into memory.
Dim doc As New Document(stream)

' You can close the stream now, it is no longer needed because the document is in memory.
stream.Close()

' ... do something with the document
//ExSummary: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 = "http://www.aspose.com/demos/.net-components/aspose.words/csharp/general/Common/Documents/DinnerInvitationDemo.doc";

// 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.
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.
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(MyDir + "Document.OpenFromWeb Out.docx");
[Visual Basic]

' This is the URL address pointing to where to find the document.
Dim url As String = "http://www.aspose.com/demos/.net-components/aspose.words/csharp/general/Common/Documents/DinnerInvitationDemo.doc"

' 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.
Dim webClient As New WebClient()

' Download the bytes from the location referenced by the URL.
Dim dataBytes() As Byte = webClient.DownloadData(url)

' Wrap the bytes representing the document in memory into a MemoryStream object.
Dim byteStream As 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.
Dim doc As New Document(byteStream)

' Convert the document to any format supported by Aspose.Words.
doc.Save(MyDir & "Document.OpenFromWeb Out.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#]

Stream stream = File.OpenRead(MyDir + "Document.LoadEncrypted.doc");
Document doc = new Document(stream, new LoadOptions("qwerty"));
stream.Close();
[Visual Basic]

Dim stream As Stream = File.OpenRead(MyDir & "Document.LoadEncrypted.doc")
Dim doc As New Document(stream, New LoadOptions("qwerty"))
stream.Close()
Opens an HTML document with images from a stream using a base URI.
[C#]

// 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.
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;
Document doc = new Document(stream, loadOptions);

// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();

// Save in the DOC format.
doc.Save(MyDir + "Document.OpenFromStreamWithBaseUri Out.doc");
[Visual Basic]

' 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>
Dim fileName As String = MyDir & "Document.OpenFromStreamWithBaseUri.html"

' Open the stream.
Dim stream As 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.
Dim loadOptions As New LoadOptions()
loadOptions.BaseUri = MyDir
Dim doc As New Document(stream, loadOptions)

' You can close the stream now, it is no longer needed because the document is in memory.
stream.Close()

' Save in the DOC format.
doc.Save(MyDir & "Document.OpenFromStreamWithBaseUri Out.doc")
Shows how to insert the HTML conntents 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.
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(MyDir + "Document.HtmlPageFromWebpage Out.doc");
[Visual Basic]

' The url of the page to load
Dim url As String = "http://www.aspose.com/"

' Create a WebClient object to easily extract the HTML from the page.
Dim client As New WebClient()
Dim pageSource As String = client.DownloadString(url)
client.Dispose()

' Get the HTML as bytes for loading into a stream.
Dim encoding As Encoding = client.Encoding
Dim pageBytes() As Byte = encoding.GetBytes(pageSource)

' Load the HTML into a stream.
Dim stream As New MemoryStream(pageBytes)

' The baseUri property should be set to ensure any relative img paths are retrieved correctly.
Dim options As New LoadOptions(Aspose.Words.LoadFormat.Html, "", url)

' Load the HTML document from stream and pass the LoadOptions object.
Dim doc As 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(MyDir & "Document.HtmlPageFromWebpage Out.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 document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).
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.
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.
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.
ResourceLoadingCallback (inherited from DocumentBase) | Allows to control how external resources are loaded.
Revisions | Gets a 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.
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.
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.
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(MyDir + "Document.DetachTemplate Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.AttachedTemplate = ""
doc.Save(MyDir & "Document.DetachTemplate Out.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;}

Remarks

Aspose.Words does not use this flag to update styles upon document loading.

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty prop in doc.BuiltInDocumentProperties)
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);

Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty prop in doc.CustomDocumentProperties)
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For Each prop As DocumentProperty In doc.BuiltInDocumentProperties
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value)
Next prop

Console.WriteLine("3. Custom Properties")
For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value)
Next prop

See Also

Document Class | Aspose.Words Namespace


CompatibilityOptions Property

Aspose.Words

Document.CompatibilityOptions Property

Provides 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;}

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty prop in doc.BuiltInDocumentProperties)
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);

Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty prop in doc.CustomDocumentProperties)
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For Each prop As DocumentProperty In doc.BuiltInDocumentProperties
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value)
Next prop

Console.WriteLine("3. Custom Properties")
For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value)
Next prop

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.

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!");
[Visual Basic]

Dim builder As 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.Signed.docx");

if (doc.DigitalSignatures.IsValid)
    Console.WriteLine("Signatures belonging to this document are valid");
else
    Console.WriteLine("Signatures belonging to this document are NOT valid");
[Visual Basic]

' Load the signed document.
Dim doc As New Document(MyDir & "Document.Signed.docx")

If doc.DigitalSignatures.IsValid Then
    Console.WriteLine("Signatures belonging to this document are valid")
Else
    Console.WriteLine("Signatures belonging to this document are NOT valid")
End If
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.Signed.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.ToString());
    Console.WriteLine("Time of signing: " + signature.SignTime);
    Console.WriteLine("Subject name: " + signature.Certificate.SubjectName.ToString());
    Console.WriteLine("Issuer name: " + signature.Certificate.IssuerName.Name);
    Console.WriteLine();
}
[Visual Basic]

' Load the document which contains signature.
Dim doc As New Document(MyDir & "Document.Signed.docx")

For Each signature As DigitalSignature 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.ToString())
    Console.WriteLine("Time of signing: " & signature.SignTime)
    Console.WriteLine("Subject name: " & signature.Certificate.SubjectName.ToString())
    Console.WriteLine("Issuer name: " & signature.Certificate.IssuerName.Name)
    Console.WriteLine()
Next signature

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 FootnoteOptions
[C#]
public FootnoteOptions EndnoteOptions {get;}

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 string[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });
[Visual Basic]

' Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode
doc.MailMerge.Execute(New String() { "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];
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", false, false);

doc.Save(MyDir + "HeaderFooter.ReplaceText Out.doc");
[Visual Basic]

' Open the template document, containing obsolete copyright information in the footer.
Dim doc As New Document(MyDir & "HeaderFooter.ReplaceText.doc")

Dim headersFooters As HeaderFooterCollection = doc.FirstSection.HeadersFooters
Dim footer As HeaderFooter = headersFooters(HeaderFooterType.FooterPrimary)
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", False, False)

doc.Save(MyDir & "HeaderFooter.ReplaceText Out.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.");
        }
    }
}
[Visual Basic]

' Open a document.
Dim doc As New Document(MyDir & "Section.BodyNodeType.doc")

' Get the first section in the document.
Dim section As Section = doc.FirstSection

' A Section is a composite node and therefore can contain child nodes.
' Section can contain only Body and HeaderFooter nodes.
For Each node As Node In section
    ' Every node has the NodeType property.
    Select Case node.NodeType
        Case NodeType.Body
            ' If the node type is Body, we can cast the node to the Body class.
            Dim body As Body = CType(node, Body)

            ' Write the content of the main story of the section to the console.
            Console.WriteLine("*** Body ***")
            Console.WriteLine(body.GetText())
            Exit Select
        Case NodeType.HeaderFooter
            ' If the node type is HeaderFooter, we can cast the node to the HeaderFooter class.
            Dim headerFooter As HeaderFooter = CType(node, HeaderFooter)

            ' Write the content of the header footer to the console.
            Console.WriteLine("*** HeaderFooter ***")
            Console.WriteLine(headerFooter.HeaderFooterType)
            Console.WriteLine(headerFooter.GetText())
            Exit Select
        Case Else
            ' Other types of nodes never occur inside a Section node.
            Throw New Exception("Unexpected node type in a section.")
    End Select
Next node

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;}

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.

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

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.

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.

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;}

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(MyDir + "MailMerge.ExecuteDataTable Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "MailMerge.ExecuteDataTable.doc")

' This example creates a table, but you would normally load table from a database.
Dim table As 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(MyDir & "MailMerge.ExecuteDataTable Out.doc")
Executes a mail merge with repeatable regions.
[C#]

public void ExecuteWithRegionsDataTable()
{
    Document doc = new Document(MyDir + "MailMerge.ExecuteWithRegions.doc");

    int orderId = 10444;

    // Perform several mail merge operations populating only part of the document each time.

    // Use DataTable as a data source.
    DataTable orderTable = GetTestOrder(orderId);
    doc.MailMerge.ExecuteWithRegions(orderTable);

    // Instead of using DataTable you can create a DataView for custom sort or filter and then mail merge.
    DataView orderDetailsView = new DataView(GetTestOrderDetails(orderId));
    orderDetailsView.Sort = "ExtendedPrice DESC";
    doc.MailMerge.ExecuteWithRegions(orderDetailsView);

    doc.Save(MyDir + "MailMerge.ExecuteWithRegionsDataTable Out.doc");
}

private static DataTable GetTestOrder(int orderId)
{
    DataTable table = ExecuteDataTable(string.Format(
        "SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId));
    table.TableName = "Orders";
    return table;
}

private static DataTable GetTestOrderDetails(int orderId)
{
    DataTable table = ExecuteDataTable(string.Format(
        "SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId));
    table.TableName = "OrderDetails";
    return table;
}

/// <summary>
/// Utility function that creates a connection, command,
/// executes the command and return the result in a DataTable.
/// </summary>
private static DataTable ExecuteDataTable(string commandText)
{
    // Open the database connection.
    string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
        DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Create and execute a command.
    OleDbCommand cmd = new OleDbCommand(commandText, conn);
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable table = new DataTable();
    da.Fill(table);

    // Close the database.
    conn.Close();

    return table;
}
[Visual Basic]

Public Sub ExecuteWithRegionsDataTable()
    Dim doc As New Document(MyDir & "MailMerge.ExecuteWithRegions.doc")

    Dim orderId As Integer = 10444

    ' Perform several mail merge operations populating only part of the document each time.

    ' Use DataTable as a data source.
    Dim orderTable As DataTable = GetTestOrder(orderId)
    doc.MailMerge.ExecuteWithRegions(orderTable)

    ' Instead of using DataTable you can create a DataView for custom sort or filter and then mail merge.
    Dim orderDetailsView As New DataView(GetTestOrderDetails(orderId))
    orderDetailsView.Sort = "ExtendedPrice DESC"
    doc.MailMerge.ExecuteWithRegions(orderDetailsView)

    doc.Save(MyDir & "MailMerge.ExecuteWithRegionsDataTable Out.doc")
End Sub

Private Shared Function GetTestOrder(ByVal orderId As Integer) As DataTable
    Dim table As DataTable = ExecuteDataTable(String.Format("SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId))
    table.TableName = "Orders"
    Return table
End Function

Private Shared Function GetTestOrderDetails(ByVal orderId As Integer) As DataTable
    Dim table As DataTable = ExecuteDataTable(String.Format("SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId))
    table.TableName = "OrderDetails"
    Return table
End Function

''' <summary>
''' Utility function that creates a connection, command,
''' executes the command and return the result in a DataTable.
''' </summary>
Private Shared Function ExecuteDataTable(ByVal commandText As String) As DataTable
    ' Open the database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Create and execute a command.
    Dim cmd As New OleDbCommand(commandText, conn)
    Dim da As New OleDbDataAdapter(cmd)
    Dim table As New DataTable()
    da.Fill(table)

    ' Close the database.
    conn.Close()

    Return table
End Function

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.

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

' This property will return the full path and file name where the document was loaded from.
Dim originalFilePath As String = doc.OriginalFileName
' Let's get just the file name from the full path.
Dim originalFileName As String = Path.GetFileName(originalFilePath)

' This is the original LoadFormat of the document.
Dim loadFormat As 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(MyDir + "Document.WithFileExtension Out" + FileFormatUtil.SaveFormatToExtension(saveFormat));
[Visual Basic]

' 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
Dim docStream As FileStream = File.OpenRead(MyDir & "Document.FileWithoutExtension") ' The file format of this document is actually ".doc"
Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(docStream)

' Retrieve the LoadFormat of the document.
Dim loadFormat As 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.
Dim fileExtension As String = FileFormatUtil.LoadFormatToExtension(loadFormat)
' Now convert this extension into the corresponding SaveFormat enumeration
Dim saveFormat As 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.
Dim doc As New Document(docStream)

' Save the document with the original file name, " Out" and the document's file extension.
doc.Save(MyDir & "Document.WithFileExtension Out" & 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;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

' This property will return the full path and file name where the document was loaded from.
Dim originalFilePath As String = doc.OriginalFileName
' Let's get just the file name from the full path.
Dim originalFileName As String = Path.GetFileName(originalFilePath)

' This is the original LoadFormat of the document.
Dim loadFormat As 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.

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;
[Visual Basic]

Dim doc As 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.
Dim pageCount As Integer = 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;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim protectionType As ProtectionType = doc.ProtectionType

See Also

Document Class | Aspose.Words Namespace | Protect | Unprotect | WriteProtection


Revisions Property

Aspose.Words

Document.Revisions Property

Gets a 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.

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;
[Visual Basic]

Dim doc As 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());
[Visual Basic]

' Open the document.
Dim doc As 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.
Dim lastSectionIdx As Integer = doc.Sections.Count - 1
Dim newSection As Section = 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;}

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. The changes that you make via Aspose.Words are never tracked as revisions.

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 (DictionaryEntry entry in doc.Variables)
{
    string name = entry.Key.ToString();
    string value = entry.Value.ToString();

    // Do something useful.
    Console.WriteLine("Name: {0}, Value: {1}", name, value);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

For Each entry As DictionaryEntry In doc.Variables
    Dim name As String = entry.Key.ToString()
    Dim value As String = entry.Value.ToString()

    ' Do something useful.
    Console.WriteLine("Name: {0}, Value: {1}", name, value)
Next entry

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.

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(MyDir + "Document.SetZoom Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.ViewOptions.ViewType = ViewType.PageLayout
doc.ViewOptions.ZoomPercent = 50
doc.Save(MyDir & "Document.SetZoom Out.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;}

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 | Appends the specified document to the end of this document.
Clone | Overloaded. Performs a deep copy of the Document.
Clone (inherited from Node) | Overloaded. Creates a duplicate of the node.
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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
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.
RemoveUnusedResources | Removes unused styles and lists from the document.
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.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.
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 | 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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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");
doc.AcceptAllRevisions();
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.AcceptAllRevisions()

See Also

Document Class | Aspose.Words Namespace


Document.AppendDocument Method

Appends the specified document to the end of this document.

[Visual Basic]
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(MyDir + "Document.AppendDocument Out.doc");
[Visual Basic]

' The document that the content will be appended to.
Dim dstDoc As New Document(MyDir & "Document.doc")
' The document to append.
Dim srcDoc As 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(MyDir & "Document.AppendDocument Out.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"));
// 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(MyDir + "Document.AppendDocumentsFromFolder Out.doc");
[Visual Basic]

' Lets start with a simple template and append all the documents in a folder to this document.
Dim baseDoc As New Document()

' Add some content to the template.
Dim builder As 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.
Dim files As New ArrayList(Directory.GetFiles(MyDir, "*.doc"))
' 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.
For Each fileName As String 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.
    Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(fileName)
    If info.IsEncrypted Then
        Continue For
    End If

    Dim subDoc As New Document(fileName)
    baseDoc.AppendDocument(subDoc, ImportFormatMode.UseDestinationStyles)
Next fileName

' Save the combined document to disk.
baseDoc.Save(MyDir & "Document.AppendDocumentsFromFolder Out.doc")

See Also

Document Class | Aspose.Words Namespace


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();
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim clone As Document = doc.Clone()

See Also

Document Class | Aspose.Words Namespace | Document.Clone 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();
[Visual Basic]

' Create a blank document then remove all nodes from it, the result will be a completely empty document.
Dim doc As 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.
Color cellShadingBefore = firstCell.CellFormat.Shading.BackgroundPatternColor;
Console.WriteLine("Cell shading before style expansion: " + cellShadingBefore.ToString());

// 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.
Color cellShadingAfter = firstCell.CellFormat.Shading.BackgroundPatternColor;
Console.WriteLine("Cell shading after style expansion: " + cellShadingAfter.ToString());
[Visual Basic]

Dim doc As New Document(MyDir & "Table.TableStyle.docx")

' Get the first cell of the first table in the document.
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
Dim firstCell As Cell = 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.
Dim cellShadingBefore As Color = firstCell.CellFormat.Shading.BackgroundPatternColor
Console.WriteLine("Cell shading before style expansion: " & cellShadingBefore.ToString())

' 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.
Dim cellShadingAfter As Color = firstCell.CellFormat.Shading.BackgroundPatternColor
Console.WriteLine("Cell shading after style expansion: " & cellShadingAfter.ToString())

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);

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(MyDir + "Rendering.RenderToScale Out.png");
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim pageInfo As PageInfo = doc.GetPageInfo(0)

' Let's say we want the image at 50% zoom.
Const MyScale As Single = 0.50f

' Let's say we want the image at this resolution.
Const MyResolution As Single = 200.0f

Dim pageSize As Size = pageInfo.GetSizeInPixels(MyScale, MyResolution)

Using img As New Bitmap(pageSize.Width, pageSize.Height)
    img.SetResolution(MyResolution, MyResolution)

    Using gr As Graphics = 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)
    End Using

    img.Save(MyDir & "Rendering.RenderToScale Out.png")
End Using

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(MyDir + "Document.JoinRunsWithSameFormatting Out.html");
[Visual Basic]

' 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.
Dim doc As New Document(MyDir & "Rendering.doc")

' This is for illustration purposes only, remember how many run nodes we had in the original document.
Dim runsBefore As Integer = 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.
Dim joinCount As Integer = doc.JoinRunsWithSameFormatting()

' This is for illustration purposes only, see how many runs are left after joining.
Dim runsAfter As Integer = 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(MyDir & "Document.JoinRunsWithSameFormatting Out.html")

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();
[Visual Basic]

Dim doc As 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);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim printerSettings As 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");
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim printerSettings As 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");
[Visual Basic]

Dim doc As 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(MyDir + "Section.Protect Out.doc");
[Visual Basic]

' Create a blank document
Dim doc As New Document()

' Insert two sections with some text
Dim builder As 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(MyDir & "Section.Protect Out.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");
[Visual Basic]

Dim doc As 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();

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();
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.RemoveMacros()

See Also

Document Class | Aspose.Words Namespace


Document.RemoveUnusedResources Method

Removes unused styles and lists from the document.

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

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);

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(MyDir + "Rendering.RenderToScale Out.png");
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim pageInfo As PageInfo = doc.GetPageInfo(0)

' Let's say we want the image at 50% zoom.
Const MyScale As Single = 0.50f

' Let's say we want the image at this resolution.
Const MyResolution As Single = 200.0f

Dim pageSize As Size = pageInfo.GetSizeInPixels(MyScale, MyResolution)

Using img As New Bitmap(pageSize.Width, pageSize.Height)
    img.SetResolution(MyResolution, MyResolution)

    Using gr As Graphics = 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)
    End Using

    img.Save(MyDir & "Rendering.RenderToScale Out.png")
End Using
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;

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(MyDir + "Rendering.Thumbnails Out.png");
    }
}
[Visual Basic]

' The user opens or builds a document.
Dim doc As New Document(MyDir & "Rendering.doc")

' This defines the number of columns to display the thumbnails in.
Const thumbColumns As Integer = 2

' Calculate the required number of rows for thumbnails.
' We can now get the number of pages in the document.
Dim remainder As Integer
Dim thumbRows As Integer = Math.DivRem(doc.PageCount, thumbColumns, remainder)
If remainder > 0 Then
    thumbRows += 1
End If

' Lets say I want thumbnails to be of this zoom.
Const scale As Single = 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.
Dim thumbSize As Size = doc.GetPageInfo(0).GetSizeInPixels(scale, 96)

' Calculate the size of the image that will contain all the thumbnails.
Dim imgWidth As Integer = thumbSize.Width * thumbColumns
Dim imgHeight As Integer = thumbSize.Height * thumbRows

Using img As 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 gr As Graphics = 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 pageIndex As Integer = 0 To doc.PageCount - 1
            Dim columnIdx As Integer
            Dim rowIdx As Integer = Math.DivRem(pageIndex, thumbColumns, columnIdx)

            ' Specify where we want the thumbnail to appear.
            Dim thumbLeft As Single = columnIdx * thumbSize.Width
            Dim thumbTop As Single = rowIdx * thumbSize.Height

            Dim size As SizeF = doc.RenderToScale(pageIndex, gr, thumbLeft, thumbTop, scale)

            ' Draw the page rectangle.
            gr.DrawRectangle(Pens.Black, thumbLeft, thumbTop, size.Width, size.Height)
        Next pageIndex

        img.Save(MyDir & "Rendering.Thumbnails Out.png")
    End Using
End Using

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 rendrered 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 occupised 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");

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, antialiasing, 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 millimiters.
        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(MyDir + "Rendering.RenderToSize Out.png");
    }
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Using bmp As New Bitmap(700, 700)
    ' User has some sort of a Graphics object. In this case created from a bitmap.
    Using gr As Graphics = Graphics.FromImage(bmp)
        ' The user can specify any options on the Graphics object including
        ' transform, antialiasing, 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.
        Dim returnedScale As Single = 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 millimiters.
        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(MyDir & "Rendering.RenderToSize Out.png")
    End Using
End Using

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");

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;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

Dim dstStream As 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;

// Read the stream back into an image.
Image image = Image.FromStream(stream);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim stream As New MemoryStream()
doc.Save(stream, SaveFormat.Bmp)

' Rewind the stream and create a .NET image from it.
stream.Position = 0

' Read the stream back into an image.
Dim image As Image = Image.FromStream(stream)
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(MyDir + "Rendering.XpsDefaultOptions Out.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(MyDir + "Rendering.XpsCustomOptions Out.xps", xpsOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save document to file in the Xps format with default options
doc.Save(MyDir & "Rendering.XpsDefaultOptions Out.xps")

' Save document to stream in the Xps format with default options
Dim docStream As 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
Dim xpsOptions As New XpsSaveOptions()
xpsOptions.PageIndex = 0
xpsOptions.PageCount = 1
doc.Save(MyDir & "Rendering.XpsCustomOptions Out.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(MyDir + "Rendering.PdfDefaultOptions Out.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(MyDir + "Rendering.PdfCustomOptions Out.pdf", pdfOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")

' Option 1: Save document to file in the PDF format with default options
doc.Save(MyDir & "Rendering.PdfDefaultOptions Out.pdf")

' Option 2: Save the document to stream in the PDF format with default options
Dim stream As 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
Dim pdfOptions As New PdfSaveOptions()
pdfOptions.PageIndex = 0
pdfOptions.PageCount = 1
pdfOptions.PreserveFormFields = True
doc.Save(MyDir & "Rendering.PdfCustomOptions Out.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(MyDir + "Rendering.JpegDefaultOptions Out.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(MyDir + "Rendering.JpegCustomOptions Out.jpg", imageOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save as a Jpeg image file with default options
doc.Save(MyDir & "Rendering.JpegDefaultOptions Out.jpg")

' Save document to stream as a Jpeg with default options
Dim docStream As 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.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg)
imageOptions.PageIndex = 2
imageOptions.PageCount = 1
imageOptions.JpegQuality = 80
doc.Save(MyDir & "Rendering.JpegCustomOptions Out.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(MyDir + "Rendering.SaveToPdfStreamOnePage Out.pdf"))
{
    PdfSaveOptions options = new PdfSaveOptions();
    options.PageIndex = 2;
    options.PageCount = 1;
    doc.Save(stream, options);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Using stream As Stream = File.Create(MyDir & "Rendering.SaveToPdfStreamOnePage Out.pdf")
    Dim options As New PdfSaveOptions()
    options.PageIndex = 2
    options.PageCount = 1
    doc.Save(stream, options)
End Using

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(MyDir + "Document.OpenFromFile Out.doc");
[Visual Basic]

doc.Save(MyDir & "Document.OpenFromFile Out.doc")
Converts a whole document from DOC to PDF using default options.
[C#]

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

doc.Save(MyDir + "Document.Doc2PdfSave Out.pdf");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

doc.Save(MyDir & "Document.Doc2PdfSave Out.pdf")
Converts from DOC to MHTML format.
[C#]

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

doc.Save(MyDir + "Document.ConvertToMhtml Out.mht");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

doc.Save(MyDir & "Document.ConvertToMhtml Out.mht")
Converts a whole document to PDF using default options.
[C#]

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

doc.Save(MyDir + "Rendering.SaveToPdfDefault Out.pdf");
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

doc.Save(MyDir & "Rendering.SaveToPdfDefault Out.pdf")
Converts a whole document into a multipage TIFF file using default options.
[C#]

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

doc.Save(MyDir + "Rendering.SaveToTiffDefault Out.tiff");
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

doc.Save(MyDir & "Rendering.SaveToTiffDefault Out.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(MyDir + "Rendering.XpsDefaultOptions Out.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(MyDir + "Rendering.XpsCustomOptions Out.xps", xpsOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save document to file in the Xps format with default options
doc.Save(MyDir & "Rendering.XpsDefaultOptions Out.xps")

' Save document to stream in the Xps format with default options
Dim docStream As 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
Dim xpsOptions As New XpsSaveOptions()
xpsOptions.PageIndex = 0
xpsOptions.PageCount = 1
doc.Save(MyDir & "Rendering.XpsCustomOptions Out.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(MyDir + "Rendering.PdfDefaultOptions Out.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(MyDir + "Rendering.PdfCustomOptions Out.pdf", pdfOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")

' Option 1: Save document to file in the PDF format with default options
doc.Save(MyDir & "Rendering.PdfDefaultOptions Out.pdf")

' Option 2: Save the document to stream in the PDF format with default options
Dim stream As 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
Dim pdfOptions As New PdfSaveOptions()
pdfOptions.PageIndex = 0
pdfOptions.PageCount = 1
pdfOptions.PreserveFormFields = True
doc.Save(MyDir & "Rendering.PdfCustomOptions Out.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(MyDir + "Rendering.JpegDefaultOptions Out.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(MyDir + "Rendering.JpegCustomOptions Out.jpg", imageOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save as a Jpeg image file with default options
doc.Save(MyDir & "Rendering.JpegDefaultOptions Out.jpg")

' Save document to stream as a Jpeg with default options
Dim docStream As 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.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg)
imageOptions.PageIndex = 2
imageOptions.PageCount = 1
imageOptions.JpegQuality = 80
doc.Save(MyDir & "Rendering.JpegCustomOptions Out.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(MyDir + "Document.ConvertToHtml Out.html", SaveFormat.Html);
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

doc.Save(MyDir & "Document.ConvertToHtml Out.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.HeadingsOutlineLevels = 3;
options.ExpandedOutlineLevels = 1;

doc.Save(MyDir + "Rendering.SaveToPdfWithOutline Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()
options.HeadingsOutlineLevels = 3
options.ExpandedOutlineLevels = 1

doc.Save(MyDir & "Rendering.SaveToPdfWithOutline Out.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);
options.TiffCompression = TiffCompression.Ccitt3;
options.PageIndex = 0;
options.PageCount = 1;

doc.Save(MyDir + "Rendering.SaveToTiffCompression Out.tiff", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Tiff)
options.TiffCompression = TiffCompression.Ccitt3
options.PageIndex = 0
options.PageCount = 1

doc.Save(MyDir & "Rendering.SaveToTiffCompression Out.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);
options.PageCount = 1;

for (int i = 0; i < doc.PageCount; i++)
{
    options.PageIndex = i;
    doc.Save(MyDir + "Rendering.SaveToEmf." + i.ToString() + " Out.emf", options);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Emf)
options.PageCount = 1

For i As Integer = 0 To doc.PageCount - 1
    options.PageIndex = i
    doc.Save(MyDir & "Rendering.SaveToEmf." & i.ToString() & " Out.emf", options)
Next i
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(MyDir + "Rendering.XpsDefaultOptions Out.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(MyDir + "Rendering.XpsCustomOptions Out.xps", xpsOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save document to file in the Xps format with default options
doc.Save(MyDir & "Rendering.XpsDefaultOptions Out.xps")

' Save document to stream in the Xps format with default options
Dim docStream As 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
Dim xpsOptions As New XpsSaveOptions()
xpsOptions.PageIndex = 0
xpsOptions.PageCount = 1
doc.Save(MyDir & "Rendering.XpsCustomOptions Out.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(MyDir + "Rendering.PdfDefaultOptions Out.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(MyDir + "Rendering.PdfCustomOptions Out.pdf", pdfOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")

' Option 1: Save document to file in the PDF format with default options
doc.Save(MyDir & "Rendering.PdfDefaultOptions Out.pdf")

' Option 2: Save the document to stream in the PDF format with default options
Dim stream As 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
Dim pdfOptions As New PdfSaveOptions()
pdfOptions.PageIndex = 0
pdfOptions.PageCount = 1
pdfOptions.PreserveFormFields = True
doc.Save(MyDir & "Rendering.PdfCustomOptions Out.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(MyDir + "Rendering.JpegDefaultOptions Out.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(MyDir + "Rendering.JpegCustomOptions Out.jpg", imageOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save as a Jpeg image file with default options
doc.Save(MyDir & "Rendering.JpegDefaultOptions Out.jpg")

' Save document to stream as a Jpeg with default options
Dim docStream As 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.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg)
imageOptions.PageIndex = 2
imageOptions.PageCount = 1
imageOptions.JpegQuality = 80
doc.Save(MyDir & "Rendering.JpegCustomOptions Out.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.
doc.Save(Response, "MailMerge.ExecuteArray Out.doc", ContentDisposition.Inline, null);
[Visual Basic]

' Open an existing document.
Dim doc As 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.
doc.Save(Response, "MailMerge.ExecuteArray Out.doc", ContentDisposition.Inline, Nothing)

See Also

Document Class | Aspose.Words Namespace | Document.Save Overload List


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 any document. Note that the password is not required.

[C#]

doc.Unprotect();
[Visual Basic]

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.

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.

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();
[Visual Basic]

Dim doc As 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(MyDir + "Rendering.UpdateFields Out.pdf");
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

' This updates all fields in the document.
doc.UpdateFields()

doc.Save(MyDir & "Rendering.UpdateFields Out.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();
[Visual Basic]

' Use a blank document
Dim doc As New Document()

' Create a document builder to insert content with into document.
Dim builder As 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))
{
    // 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++;
    }

}
[Visual Basic]

Dim doc As New Document(MyDir & "Lists.PrintOutAllLists.doc")
doc.UpdateListLabels()
Dim listParaCount As Integer = 1

For Each paragraph As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 Then
        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.
        Dim paragraphText As String = paragraph.ToString(SaveFormat.Text).Trim()
        Console.WriteLine("Exported Text: " & paragraphText)

        Dim label As ListLabel = 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 += 1
    End If

Next paragraph

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(MyDir + "Rendering.UpdatePageLayout1 Out.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(MyDir + "Rendering.UpdatePageLayout2 Out.pdf");
[Visual Basic]

Dim doc As 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(MyDir & "Rendering.UpdatePageLayout1 Out.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(MyDir & "Rendering.UpdatePageLayout2 Out.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();
[Visual Basic]

Dim doc As 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();

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.

See Also

Document Class | Aspose.Words Namespace | Document.UpdateThumbnail Overload List


Document.UpdateWordCount Method

Updates word count properties of the document.

[Visual Basic]
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.

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);
[Visual Basic]

Dim doc As 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


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.

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.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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.

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 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++;
}
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

Dim fonts As FontInfoCollection = doc.FontInfos
Dim fontIndex As Integer = 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.
For Each info As FontInfo 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 += 1
Next info

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(MyDir + "Lists.SpecifyListLevel Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next i

' This is a way to stop list formatting.
builder.ListFormat.List = Nothing

builder.Document.Save(MyDir & "Lists.SpecifyListLevel Out.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 HandleNodeChanging_FontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(MyDir + "Document.FontChanger Out.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 HandleNodeChanging_FontChanger : 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
    }
}
[Visual Basic]

Public Sub TestNodeChangingInDocument()
    ' Create a blank document object
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    ' Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = New HandleNodeChanging_FontChanger()

    ' Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>")

    doc.Save(MyDir & "Document.FontChanger Out.doc")

    ' Check that the inserted content has the correct formatting
    Dim run As Run = CType(doc.GetChild(NodeType.Run, 0, True), Run)
    Assert.AreEqual(24.0, run.Font.Size)
    Assert.AreEqual("Arial", run.Font.Name)
End Sub

Public Class HandleNodeChanging_FontChanger
    Implements INodeChangingCallback
    ' Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    Private Sub NodeInserted(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserted
        ' Change the font of inserted text contained in the Run nodes.
        If args.Node.NodeType = NodeType.Run Then
            Dim font As Aspose.Words.Font = (CType(args.Node, Run)).Font
            font.Size = 24
            font.Name = "Arial"
        End If
    End Sub

    Private Sub NodeInserting(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserting
        ' Do Nothing
    End Sub

    Private Sub NodeRemoved(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoved
        ' Do Nothing
    End Sub

    Private Sub NodeRemoving(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoving
        ' Do Nothing
    End Sub
End Class

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.

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;}

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);
[Visual Basic]

Dim doc As New Document()
Dim styles As StyleCollection = doc.Styles

For Each style As Style In styles
    Console.WriteLine(style.Name)
Next style
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(MyDir + "Lists.ParagraphStyleBulleted Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a paragraph style and specify some formatting for it.
Dim style As 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(MyDir & "Lists.ParagraphStyleBulleted Out.doc")

See Also

DocumentBase Class | Aspose.Words Namespace | StyleCollection | Style


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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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 manually append the content from one document to the end of another document.

[C#]

/// <summary>
/// A manual implementation of the Document.AppendDocument function which shows the general
/// steps of how a document is appended to another.
/// </summary>
/// <param name="dstDoc">The destination document where to append to.</param>
/// <param name="srcDoc">The source document.</param>
/// <param name="mode">The import mode to use when importing content from another document.</param>
public void AppendDocument(Document dstDoc, Document srcDoc, ImportFormatMode mode)
{
    // Loop through all sections in the source document.
    // Section nodes are immediate children of the Document node so we can just enumerate the Document.
    foreach (Section srcSection in srcDoc)
    {
        // Because we are copying a section from one document to another,
        // it is required to import the Section node into the destination document.
        // This adjusts any document-specific references to styles, lists, etc.
        //
        // Importing a node creates a copy of the original node, but the copy
        // is ready to be inserted into the destination document.
        Node dstSection = dstDoc.ImportNode(srcSection, true, mode);

        // Now the new section node can be appended to the destination document.
        dstDoc.AppendChild(dstSection);
    }
}
[Visual Basic]

''' <summary>
''' A manual implementation of the Document.AppendDocument function which shows the general
''' steps of how a document is appended to another.
''' </summary>
''' <param name="dstDoc">The destination document where to append to.</param>
''' <param name="srcDoc">The source document.</param>
''' <param name="mode">The import mode to use when importing content from another document.</param>
Public Sub AppendDocument(ByVal dstDoc As Document, ByVal srcDoc As Document, ByVal mode As ImportFormatMode)
    ' Loop through all sections in the source document.
    ' Section nodes are immediate children of the Document node so we can just enumerate the Document.
    For Each srcSection As Section In srcDoc
        ' Because we are copying a section from one document to another,
        ' it is required to import the Section node into the destination document.
        ' This adjusts any document-specific references to styles, lists, etc.
        '
        ' Importing a node creates a copy of the original node, but the copy
        ' is ready to be inserted into the destination document.
        Dim dstSection As Node = dstDoc.ImportNode(srcSection, True, mode)

        ' Now the new section node can be appended to the destination document.
        dstDoc.AppendChild(dstSection)
    Next srcSection
End Sub
Shows how to manually prepend the content from one document to the beginning of another document.
[C#]

public static void PrependDocumentMain()
{
    Document dstDoc = new Document(gDataDir + "TestFile.Destination.doc");
    Document srcDoc = new Document(gDataDir + "TestFile.Source.doc");

    // Append the source document to the destination document. This causes the result to have line spacing problems.
    dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);

    // Instead prepend the content of the destination document to the start of the source document.
    // This results in the same joined document but with no line spacing issues.
    PrependDocument(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting);
}

/// <summary>
/// A modified version of the AppendDocument method which prepends the content of one document to the start
/// of another.
/// </summary>
/// <param name="dstDoc">The destination document where to prepend the source document to.</param>
/// <param name="srcDoc">The source document.</param>
public static void PrependDocument(Document dstDoc, Document srcDoc, ImportFormatMode mode)
{
    // Loop through all sections in the source document.
    // Section nodes are immediate children of the Document node so we can just enumerate the Document.
    ArrayList sections = new ArrayList(srcDoc.Sections.ToArray());

    // Reverse the order of the sections so they are prepended to start of the destination document in the correct order.
    sections.Reverse();

    foreach (Section srcSection in sections)
    {
        // Import the nodes from the source document.
        Node dstSection = dstDoc.ImportNode(srcSection, true, mode);

        // Now the new section node can be prepended to the destination document.
        // Note how PrependChild is used instead of AppendChild. This is the only line changed compared
        // to the original method.
        dstDoc.PrependChild(dstSection);
    }
}
[Visual Basic]

Public Shared Sub PrependDocumentMain()
    Dim dstDoc As New Document(gDataDir & "TestFile.Destination.doc")
    Dim srcDoc As New Document(gDataDir & "TestFile.Source.doc")

    ' Append the source document to the destination document. This causes the result to have line spacing problems.
    dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting)

    ' Instead prepend the content of the destination document to the start of the source document.
    ' This results in the same joined document but with no line spacing issues.
    PrependDocument(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting)
End Sub

''' <summary>
''' A modified version of the AppendDocument method which prepends the content of one document to the start
''' of another.
''' </summary>
''' <param name="dstDoc">The destination document where to prepend the source document to.</param>
''' <param name="srcDoc">The source document.</param>
Public Shared Sub PrependDocument(ByVal dstDoc As Document, ByVal srcDoc As Document, ByVal mode As ImportFormatMode)
    ' Loop through all sections in the source document.
    ' Section nodes are immediate children of the Document node so we can just enumerate the Document.
    Dim sections As New ArrayList(srcDoc.Sections.ToArray())

    ' Reverse the order of the sections so they are prepended to start of the destination document in the correct order.
    sections.Reverse()

    For Each srcSection As Section In sections
        ' Import the nodes from the source document.
        Dim dstSection As Node = dstDoc.ImportNode(srcSection, True, mode)

        ' Now the new section node can be prepended to the destination document.
        ' Note how PrependChild is used instead of AppendChild. This is the only line changed compared
        ' to the original method.
        dstDoc.PrependChild(dstSection)
    Next srcSection
End Sub

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");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.StartBookmark("MyBookmark")
builder.Writeln("Text inside a bookmark.")
builder.EndBookmark("MyBookmark")
Inserts HTML into a document using DocumentBuilder.
[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>");

doc.Save(MyDir + "DocumentBuilder.InsertHtml Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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>")

doc.Save(MyDir & "DocumentBuilder.InsertHtml Out.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(MyDir + "DocumentBuilder.CreateSimpleTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.CreateSimpleTable Out.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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.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.
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.
InsertCheckBox | Inserts a checkbox form field at the current position.
InsertComboBox | Inserts a combobox form field at the current position.
InsertField | Overloaded. Inserts a Word field into a document.
InsertFootnote | Inserts a footnote or endnote into the document.
InsertHtml | Inserts 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.
InsertParagraph | Inserts a paragraph break 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.
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.");
[Visual Basic]

Dim builder As New DocumentBuilder()

' Specify font formatting before adding text.
Dim font As Aspose.Words.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(MyDir + "DocumentBuilder.HeadersAndFooters Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.HeadersAndFooters Out.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();
[Visual Basic]

' Use a blank document
Dim doc As New Document()

' Create a document builder to insert content with into document.
Dim builder As 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(MyDir + "DocumentBuilder.FillingDocument Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.FillingDocument.doc")
Dim builder As 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(MyDir & "DocumentBuilder.FillingDocument Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.StartTable()
builder.InsertCell()

' Set the cell formatting
Dim cellFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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();

// 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]);
builder.CurrentNode.Range.Replace("bad", "good", false, true);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(MyDir + "DocumentBuilder.WorkingWithNodes Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.WorkingWithNodes.doc")
Dim builder As New DocumentBuilder(doc)

' Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete")
builder.CurrentParagraph.Remove()

' 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))
builder.CurrentNode.Range.Replace("bad", "good", False, True)

' Mark the beginning of the document.
builder.MoveToDocumentStart()
builder.Writeln("Start of document.")

' Mark the ending of the document.
builder.MoveToDocumentEnd()
builder.Writeln("End of document.")

doc.Save(MyDir & "DocumentBuilder.WorkingWithNodes Out.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();

// 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]);
builder.CurrentNode.Range.Replace("bad", "good", false, true);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(MyDir + "DocumentBuilder.WorkingWithNodes Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.WorkingWithNodes.doc")
Dim builder As New DocumentBuilder(doc)

' Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete")
builder.CurrentParagraph.Remove()

' 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))
builder.CurrentNode.Range.Replace("bad", "good", False, True)

' Mark the beginning of the document.
builder.MoveToDocumentStart()
builder.Writeln("Start of document.")

' Mark the ending of the document.
builder.MoveToDocumentEnd()
builder.Writeln("End of document.")

doc.Save(MyDir & "DocumentBuilder.WorkingWithNodes Out.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 + "Hammer.wmf");

// 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;

// Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0;
shape.Top = 0;
shape.Width = builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;

builder.Document.Save(MyDir + "Image.CreateFloatingPositionSize Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "Hammer.wmf")

' 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

' Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0
shape.Top = 0
shape.Width = builder.CurrentSection.PageSetup.PageWidth
shape.Height = 50

builder.Document.Save(MyDir & "Image.CreateFloatingPositionSize Out.doc")

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;}

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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.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;}

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;}

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(MyDir + "DocumentBuilder.FillingDocument Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.FillingDocument.doc")
Dim builder As 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(MyDir & "DocumentBuilder.FillingDocument Out.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(MyDir + "Lists.ApplyDefaultBulletsAndNumbers Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "Lists.ApplyDefaultBulletsAndNumbers Out.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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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

Inserts a paragraph with a top border.

[C#]

DocumentBuilder builder = new DocumentBuilder();

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

builder.Writeln("Hello World!");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim topBorder As Border = builder.ParagraphFormat.Borders(BorderType.Top)
topBorder.Color = System.Drawing.Color.Red
topBorder.LineStyle = LineStyle.DashSmallGap
topBorder.LineWidth = 4

builder.Writeln("Hello World!")
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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As Table = builder.StartTable()
builder.InsertCell()

' Set the row formatting
Dim rowFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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;}

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.
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.
InsertCheckBox | Inserts a checkbox form field at the current position.
InsertComboBox | Inserts a combobox form field at the current position.
InsertField | Overloaded. Inserts a Word field into a document.
InsertFootnote | Inserts a footnote or endnote into the document.
InsertHtml | Inserts 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.
InsertParagraph | Inserts a paragraph break 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.
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.

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");
[Visual Basic]

Dim builder As 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(MyDir + "DocumentBuilder.InsertHyperlinkToLocalBookmark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.InsertHyperlinkToLocalBookmark Out.doc")

See Also

DocumentBuilder Class | Aspose.Words Namespace


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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.StartTable()
builder.InsertCell()

' Set the cell formatting
Dim cellFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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(MyDir + "DocumentBuilder.HeadersAndFooters Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.HeadersAndFooters Out.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();
[Visual Basic]

' Use a blank document
Dim doc As New Document()

' Create a document builder to insert content with into document.
Dim builder As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir + "DocumentBuilder.CreateSimpleTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.CreateSimpleTable Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.doc")

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertCheckBox Method

Inserts a checkbox form field at the current position.

[Visual Basic]
Public Function InsertCheckBox( _
ByVal name As String, _
ByVal defaultValue As Boolean, _
ByVal size As Integer _
) As FormField
[C#]
public FormField InsertCheckBox(
string name,
bool defaultValue,
int size
);

Parameters

name
The name of the form field. Can be an empty string.
defaultValue
Default value of the 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 a checkbox form field into a document.

[C#]

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

builder.InsertCheckBox("CheckBox", true, 0);
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.InsertCheckBox("CheckBox", True, 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 = new string[]
    {
        "-- 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("");

// Insert a check box to ensure the form filler does look after his/her footwear.
builder.InsertCheckBox("", true, 0);
builder.Writeln("My boots are always polished and nice-looking.");

builder.Document.Save(MyDir + "DocumentBuilder.CreateForm Out.doc");
[Visual Basic]

Dim builder As 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("")

Dim items() As String = { "-- 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("")

' Insert a check box to ensure the form filler does look after his/her footwear.
builder.InsertCheckBox("", True, 0)
builder.Writeln("My boots are always polished and nice-looking.")

builder.Document.Save(MyDir & "DocumentBuilder.CreateForm Out.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>>.
public void MailMergeInsertCheckBox()
{
    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(MyDir + "MailMerge.InsertCheckBox Out.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 e)
    {
        if (e.DocumentFieldName.Equals("CourseName"))
        {
            // Insert the checkbox for this merge field, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.FieldName);
            builder.InsertCheckBox(e.DocumentFieldName + mCheckBoxCount.ToString(), false, 0);
            builder.Write((string)e.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.ToString();
    }
    return dataTable;
}
[Visual Basic]

' File 'MailMerge.InsertCheckBox.doc' is a template
' containing the table with the following fields in it:
' <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
Public Sub MailMergeInsertCheckBox()
    Dim doc As New Document(MyDir & "MailMerge.InsertCheckBox.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertCheckBox()

    ' Execute mail merge with regions.
    Dim dataTable As DataTable = GetStudentCourseDataTable()
    doc.MailMerge.ExecuteWithRegions(dataTable)

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertCheckBox Out.doc")
End Sub

Private Class HandleMergeFieldInsertCheckBox
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called for each merge field in the document
    ''' when Document.MailMerge.ExecuteWithRegions is called.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        If e.DocumentFieldName.Equals("CourseName") Then
            ' Insert the checkbox for this merge field, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.FieldName)
            builder.InsertCheckBox(e.DocumentFieldName + mCheckBoxCount.ToString(), False, 0)
            builder.Write(CStr(e.FieldValue))
            mCheckBoxCount += 1
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub

    ''' <summary>
    ''' Counter for CheckBox name generation
    ''' </summary>
    Private mCheckBoxCount As Integer
End Class

''' <summary>
''' Create DataTable and fill it with data.
''' In real life this DataTable should be filled from a database.
''' </summary>
Private Shared Function GetStudentCourseDataTable() As DataTable
    Dim dataTable As New DataTable("StudentCourse")
    dataTable.Columns.Add("CourseName")
    For i As Integer = 0 To 9
        Dim datarow As DataRow = dataTable.NewRow()
        dataTable.Rows.Add(datarow)
        datarow(0) = "Course " & i.ToString()
    Next i
    Return dataTable
End Function

See Also

DocumentBuilder Class | Aspose.Words Namespace


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.
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);
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim items() As String = { "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 = new string[]
    {
        "-- 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("");

// Insert a check box to ensure the form filler does look after his/her footwear.
builder.InsertCheckBox("", true, 0);
builder.Writeln("My boots are always polished and nice-looking.");

builder.Document.Save(MyDir + "DocumentBuilder.CreateForm Out.doc");
[Visual Basic]

Dim builder As 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("")

Dim items() As String = { "-- 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("")

' Insert a check box to ensure the form filler does look after his/her footwear.
builder.InsertCheckBox("", True, 0)
builder.Writeln("My boots are always polished and nice-looking.")

builder.Document.Save(MyDir & "DocumentBuilder.CreateForm Out.doc")

See Also

DocumentBuilder Class | Aspose.Words Namespace


InsertField Method

Aspose.Words

DocumentBuilder.InsertField Method

Inserts a Word field into a document.

Overload List

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 (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

Inserts a merge field into a document using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField(@"MERGEFIELD MyFieldName \* MERGEFORMAT");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.InsertField("MERGEFIELD MyFieldName \* MERGEFORMAT")
Inserts a field into a document using DocumentBuilder.
[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 behaviour 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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.
Dim dateField As Field = 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 behaviour 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 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(MyDir + "PageSetup.PageNumbering Out.doc");
[Visual Basic]

' This document has two sections, but no page numbers yet.
Dim doc As 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".
Dim builder As New DocumentBuilder(doc)
builder.MoveToSection(0)
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary)
builder.Write("Page ")
builder.InsertField("PAGE", "")

' Set first section page numbering.
Dim section As Section = doc.Sections(0)
section.PageSetup.RestartPageNumbering = True
section.PageSetup.PageStartingNumber = 5
section.PageSetup.PageNumberStyle = NumberStyle.UppercaseRoman

' Create a header for the section 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(MyDir & "PageSetup.PageNumbering Out.doc")

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertField Overload List | Field


DocumentBuilder.InsertFootnote Method

Inserts a footnote or endnote into the document.

[Visual Basic]
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);
builder.Write("Some text");

builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text")

builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.")

See Also

DocumentBuilder Class | Aspose.Words Namespace


DocumentBuilder.InsertHtml Method

Inserts HTML string into the document.

[Visual Basic]
Public Sub InsertHtml( _
ByVal html As String _
)
[C#]
public void InsertHtml(
string html
);

Parameters

html
HTML string to insert into the document.

Remarks

You can use InsertHtml to insert an HTML fragment or whole HTML document.

Example

Inserts HTML into a document using DocumentBuilder.

[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>");

doc.Save(MyDir + "DocumentBuilder.InsertHtml Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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>")

doc.Save(MyDir & "DocumentBuilder.InsertHtml Out.doc")
Replaces text specified with regular expression with HTML.
[C#]

public void ReplaceWithInsertHtml()
{
    // Open the document.
    Document doc = new Document(MyDir + "Range.ReplaceWithInsertHtml.doc");

    doc.Range.Replace(new Regex(@"<CustomerName>"), new ReplaceWithHtmlEvaluator(), false);

    // Save the modified document.
    doc.Save(MyDir + "Range.ReplaceWithInsertHtml Out.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    /// <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 e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>");

        e.Replacement = "";
        return ReplaceAction.Replace;
    }
}
[Visual Basic]

Public Sub ReplaceWithInsertHtml()
    ' Open the document.
    Dim doc As New Document(MyDir & "Range.ReplaceWithInsertHtml.doc")

    doc.Range.Replace(New Regex("<CustomerName>"), New ReplaceWithHtmlEvaluator(), False)

    ' Save the modified document.
    doc.Save(MyDir & "Range.ReplaceWithInsertHtml Out.doc")

End Sub

Private Class ReplaceWithHtmlEvaluator
    Implements IReplacingCallback
    ''' <summary>
    ''' NOTE: This is a simplistic method that will only work well when the match
    ''' starts at the beginning of a run.
    ''' </summary>
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim builder As New DocumentBuilder(CType(e.MatchNode.Document, Document))
        builder.MoveTo(e.MatchNode)
        ' Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>")

        e.Replacement = ""
        Return ReplaceAction.Replace
    End Function
End Class
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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

See Also

DocumentBuilder Class | Aspose.Words Namespace


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(MyDir + "DocumentBuilder.InsertHyperlink Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.InsertHyperlink Out.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(MyDir + "DocumentBuilder.InsertHyperlinkToLocalBookmark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.InsertHyperlinkToLocalBookmark Out.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(MyDir + "DocumentBuilder.PushPopFont Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.PushPopFont Out.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.

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 value to request 100% scale.
height
The height if the image in points. Can be a negative 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.

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 value to request 100% scale.
height
The height if the image in points. Can be a negative 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.

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 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();

// Insert a raster image.
System.Drawing.Image rasterImage = System.Drawing.Image.FromFile(MyDir + "Aspose.Words.gif");
try
{
    builder.Write("Raster image: ");
    builder.InsertImage(rasterImage);
    builder.Writeln();
}
finally
{
    rasterImage.Dispose();
}

// Aspose.Words allows to insert a metafile too.
System.Drawing.Image metafile = System.Drawing.Image.FromFile(MyDir + "Hammer.wmf");
try
{
    builder.Write("Metafile: ");
    builder.InsertImage(metafile);
    builder.Writeln();
}
finally
{
    metafile.Dispose();
}

builder.Document.Save(MyDir + "Image.CreateFromImage Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' Insert a raster image.
Dim rasterImage As System.Drawing.Image = System.Drawing.Image.FromFile(MyDir & "Aspose.Words.gif")
Try
    builder.Write("Raster image: ")
    builder.InsertImage(rasterImage)
    builder.Writeln()
Finally
    rasterImage.Dispose()
End Try

' Aspose.Words allows to insert a metafile too.
Dim metafile As System.Drawing.Image = System.Drawing.Image.FromFile(MyDir & "Hammer.wmf")
Try
    builder.Write("Metafile: ")
    builder.InsertImage(metafile)
    builder.Writeln()
Finally
    metafile.Dispose()
End Try

builder.Document.Save(MyDir & "Image.CreateFromImage Out.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(MyDir + "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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(MyDir + "DocumentBuilder.InsertWatermark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)

Dim image As Image = Image.FromFile(MyDir & "Watermark.png")

' Insert a floating picture.
Dim shape As 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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2

doc.Save(MyDir & "DocumentBuilder.InsertWatermark Out.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 value to request 100% scale.
height
The height if the image in points. Can be a negative 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.

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 value to request 100% scale.
height
The height if the image in points. Can be a negative 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.

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 + "Aspose.Words.gif");
try
{
    builder.Write("Image from stream: ");
    builder.InsertImage(stream);
}
finally
{
    stream.Close();
}

builder.Document.Save(MyDir + "Image.CreateFromStream Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

Dim stream As Stream = File.OpenRead(MyDir & "Aspose.Words.gif")
Try
    builder.Write("Image from stream: ")
    builder.InsertImage(stream)
Finally
    stream.Close()
End Try

builder.Document.Save(MyDir & "Image.CreateFromStream Out.doc")

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 value to request 100% scale.
height
The height if the image in points. Can be a negative 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.

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 value to request 100% scale.
height
The height if the image in points. Can be a negative 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.

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("http://www.aspose.com/images/aspose-logo.gif");

doc.Save(MyDir + "DocumentBuilder.InsertImageFromUrl Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.InsertImage("http://www.aspose.com/images/aspose-logo.gif")

doc.Save(MyDir & "DocumentBuilder.InsertImageFromUrl Out.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 + "Aspose.Words.gif");
builder.Writeln();

builder.Write("Image from an internet url, automatically downloaded for you: ");
builder.InsertImage("http://www.aspose.com/Images/aspose-logo.jpg");
builder.Writeln();

builder.Document.Save(MyDir + "Image.CreateFromUrl Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

builder.Write("Image from local file: ")
builder.InsertImage(MyDir & "Aspose.Words.gif")
builder.Writeln()

builder.Write("Image from an internet url, automatically downloaded for you: ")
builder.InsertImage("http://www.aspose.com/Images/aspose-logo.jpg")
builder.Writeln()

builder.Document.Save(MyDir & "Image.CreateFromUrl Out.doc")
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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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 value to request 100% scale.
height
The height if the image in points. Can be a negative 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(MyDir + "Watermark.png",
    RelativeHorizontalPosition.Margin,
    100,
    RelativeVerticalPosition.Margin,
    100,
    200,
    100,
    WrapType.Square);
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.InsertImage(MyDir & "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(MyDir + "LogoSmall.png",
    RelativeHorizontalPosition.Margin,
    200,
    RelativeVerticalPosition.Margin,
    100,
    -1,
    -1,
    WrapType.Square);
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Pass a negative value to the width and height values to specify using the size of the source image.
builder.InsertImage(MyDir & "LogoSmall.png", RelativeHorizontalPosition.Margin, 200, RelativeVerticalPosition.Margin, 100, -1, -1, WrapType.Square)

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 value to request 100% scale.
height
The height if the image in points. Can be a negative 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.

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 + "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(MyDir + "Image.CreateLinkedImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim imageFileName As String = MyDir & "Hammer.wmf"

builder.Write("Image linked, not stored in the document: ")

Dim linkedOnly As 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: ")

Dim linkedAndStored As 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: ")

Dim stored As New Shape(builder.Document, ShapeType.Image)
stored.WrapType = WrapType.Inline
stored.ImageData.SetImage(imageFileName)

builder.InsertNode(stored)
builder.Writeln()

builder.Document.Save(MyDir & "Image.CreateLinkedImage Out.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.

public Shape InsertOleObject(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.

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.

[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.

See Also

DocumentBuilder Class | Aspose.Words Namespace | DocumentBuilder.InsertOleObject 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 = System.Drawing.Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Specify font formatting
Dim font As Aspose.Words.Font = builder.Font
font.Size = 16
font.Bold = True
font.Color = System.Drawing.Color.Blue
font.Name = "Arial"
font.Underline = Underline.Dash

' Specify paragraph formatting
Dim paragraphFormat As ParagraphFormat = builder.ParagraphFormat
paragraphFormat.FirstLineIndent = 8
paragraphFormat.Alignment = ParagraphAlignment.Justify
paragraphFormat.KeepTogether = True

builder.Writeln("A whole paragraph.")

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();
[Visual Basic]

' Use a blank document
Dim doc As New Document()

' Create a document builder to insert content with into document.
Dim builder As 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);
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", "Hello", 0)
Shows how to insert FormFields, set options annd 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);
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 = new string[]
    {
        "-- 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("");

// Insert a check box to ensure the form filler does look after his/her footwear.
builder.InsertCheckBox("", true, 0);
builder.Writeln("My boots are always polished and nice-looking.");

builder.Document.Save(MyDir + "DocumentBuilder.CreateForm Out.doc");
[Visual Basic]

Dim builder As 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("")

Dim items() As String = { "-- 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("")

' Insert a check box to ensure the form filler does look after his/her footwear.
builder.InsertCheckBox("", True, 0)
builder.Writeln("My boots are always polished and nice-looking.")

builder.Document.Save(MyDir & "DocumentBuilder.CreateForm Out.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.

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);
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.doc")
Dim builder As 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();

// 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]);
builder.CurrentNode.Range.Replace("bad", "good", false, true);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(MyDir + "DocumentBuilder.WorkingWithNodes Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.WorkingWithNodes.doc")
Dim builder As New DocumentBuilder(doc)

' Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete")
builder.CurrentParagraph.Remove()

' 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))
builder.CurrentNode.Range.Replace("bad", "good", False, True)

' Mark the beginning of the document.
builder.MoveToDocumentStart()
builder.Writeln("Start of document.")

' Mark the ending of the document.
builder.MoveToDocumentEnd()
builder.Writeln("End of document.")

doc.Save(MyDir & "DocumentBuilder.WorkingWithNodes Out.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();

// 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]);
builder.CurrentNode.Range.Replace("bad", "good", false, true);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(MyDir + "DocumentBuilder.WorkingWithNodes Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.WorkingWithNodes.doc")
Dim builder As New DocumentBuilder(doc)

' Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete")
builder.CurrentParagraph.Remove()

' 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))
builder.CurrentNode.Range.Replace("bad", "good", False, True)

' Mark the beginning of the document.
builder.MoveToDocumentStart()
builder.Writeln("Start of document.")

' Mark the ending of the document.
builder.MoveToDocumentEnd()
builder.Writeln("End of document.")

doc.Save(MyDir & "DocumentBuilder.WorkingWithNodes Out.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.

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.");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.doc")
Dim builder As 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!");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.doc")
Dim builder As 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();

// 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]);
builder.CurrentNode.Range.Replace("bad", "good", false, true);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(MyDir + "DocumentBuilder.WorkingWithNodes Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.WorkingWithNodes.doc")
Dim builder As New DocumentBuilder(doc)

' Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete")
builder.CurrentParagraph.Remove()

' 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))
builder.CurrentNode.Range.Replace("bad", "good", False, True)

' Mark the beginning of the document.
builder.MoveToDocumentStart()
builder.Writeln("Start of document.")

' Mark the ending of the document.
builder.MoveToDocumentEnd()
builder.Writeln("End of document.")

doc.Save(MyDir & "DocumentBuilder.WorkingWithNodes Out.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();

// 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]);
builder.CurrentNode.Range.Replace("bad", "good", false, true);

// Mark the beginning of the document.
builder.MoveToDocumentStart();
builder.Writeln("Start of document.");

// Mark the ending of the document.
builder.MoveToDocumentEnd();
builder.Writeln("End of document.");

doc.Save(MyDir + "DocumentBuilder.WorkingWithNodes Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.WorkingWithNodes.doc")
Dim builder As New DocumentBuilder(doc)

' Move to a bookmark and delete the parent paragraph.
builder.MoveToBookmark("ParaToDelete")
builder.CurrentParagraph.Remove()

' 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))
builder.CurrentNode.Range.Replace("bad", "good", False, True)

' Mark the beginning of the document.
builder.MoveToDocumentStart()
builder.Writeln("Start of document.")

' Mark the ending of the document.
builder.MoveToDocumentEnd()
builder.Writeln("End of document.")

doc.Save(MyDir & "DocumentBuilder.WorkingWithNodes Out.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.

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(MyDir + "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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(MyDir + "DocumentBuilder.InsertWatermark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)

Dim image As Image = Image.FromFile(MyDir & "Watermark.png")

' Insert a floating picture.
Dim shape As 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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2

doc.Save(MyDir & "DocumentBuilder.InsertWatermark Out.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(MyDir + "DocumentBuilder.HeadersAndFooters Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.HeadersAndFooters Out.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(MyDir + "DocumentBuilder.FillingDocument Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.FillingDocument.doc")
Dim builder As 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(MyDir & "DocumentBuilder.FillingDocument Out.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>>.
public void MailMergeInsertCheckBox()
{
    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(MyDir + "MailMerge.InsertCheckBox Out.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 e)
    {
        if (e.DocumentFieldName.Equals("CourseName"))
        {
            // Insert the checkbox for this merge field, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.FieldName);
            builder.InsertCheckBox(e.DocumentFieldName + mCheckBoxCount.ToString(), false, 0);
            builder.Write((string)e.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.ToString();
    }
    return dataTable;
}
[Visual Basic]

' File 'MailMerge.InsertCheckBox.doc' is a template
' containing the table with the following fields in it:
' <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
Public Sub MailMergeInsertCheckBox()
    Dim doc As New Document(MyDir & "MailMerge.InsertCheckBox.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertCheckBox()

    ' Execute mail merge with regions.
    Dim dataTable As DataTable = GetStudentCourseDataTable()
    doc.MailMerge.ExecuteWithRegions(dataTable)

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertCheckBox Out.doc")
End Sub

Private Class HandleMergeFieldInsertCheckBox
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called for each merge field in the document
    ''' when Document.MailMerge.ExecuteWithRegions is called.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        If e.DocumentFieldName.Equals("CourseName") Then
            ' Insert the checkbox for this merge field, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.FieldName)
            builder.InsertCheckBox(e.DocumentFieldName + mCheckBoxCount.ToString(), False, 0)
            builder.Write(CStr(e.FieldValue))
            mCheckBoxCount += 1
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub

    ''' <summary>
    ''' Counter for CheckBox name generation
    ''' </summary>
    Private mCheckBoxCount As Integer
End Class

''' <summary>
''' Create DataTable and fill it with data.
''' In real life this DataTable should be filled from a database.
''' </summary>
Private Shared Function GetStudentCourseDataTable() As DataTable
    Dim dataTable As New DataTable("StudentCourse")
    dataTable.Columns.Add("CourseName")
    For i As Integer = 0 To 9
        Dim datarow As DataRow = dataTable.NewRow()
        dataTable.Rows.Add(datarow)
        datarow(0) = "Course " & i.ToString()
    Next i
    Return dataTable
End Function

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 extract content between a specific field and paragraph in the document using the ExtractContent method.

[C#]

// Load in the document
Document doc = new Document(mDataDir + "TestFile.doc");

// Use a document builder to retrieve the field start of a merge field.
DocumentBuilder builder = new DocumentBuilder(doc);

// Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field.
// We could also get FieldStarts of a field using GetChildNode method as in the other examples.
builder.MoveToMergeField("Fullname", false, false);

// The builder cursor should be positioned at the start of the field.
FieldStart startField = (FieldStart)builder.CurrentNode;
Paragraph endPara = (Paragraph)doc.FirstSection.GetChild(NodeType.Paragraph, 5, true);

// Extract the content between these nodes in the document. Don't include these markers in the extraction.
ArrayList extractedNodes = ExtractContent(startField, endPara, false);

// Insert the content into a new separate document and save it to disk.
Document dstDoc = GenerateDocument(doc, extractedNodes);
dstDoc.Save(mDataDir + "TestFile.Fields Out.pdf");
[Visual Basic]

' Load in the document
Dim doc As New Document(mDataDir & "TestFile.doc")

' Use a document builder to retrieve the field start of a merge field.
Dim builder As New DocumentBuilder(doc)

' Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field.
' We could also get FieldStarts of a field using GetChildNode method as in the other examples.
builder.MoveToMergeField("Fullname", False, False)

' The builder cursor should be positioned at the start of the field.
Dim startField As FieldStart = CType(builder.CurrentNode, FieldStart)
Dim endPara As Paragraph = CType(doc.FirstSection.GetChild(NodeType.Paragraph, 5, True), Paragraph)

' Extract the content between these nodes in the document. Don't include these markers in the extraction.
Dim extractedNodes As ArrayList = ExtractContent(startField, endPara, False)

' Insert the content into a new separate document and save it to disk.
Dim dstDoc As Document = GenerateDocument(doc, extractedNodes)
dstDoc.Save(mDataDir & "TestFile.Fields Out.pdf")

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.");
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.doc")
Dim builder As 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(MyDir + "DocumentBuilder.HeadersAndFooters Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.HeadersAndFooters Out.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(MyDir + "DocumentBuilder.PushPopFont Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.PushPopFont Out.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(MyDir + "DocumentBuilder.PushPopFont Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.PushPopFont Out.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");
[Visual Basic]

Dim builder As 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(MyDir + "DocumentBuilder.InsertHyperlinkToLocalBookmark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.InsertHyperlinkToLocalBookmark Out.doc")

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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.StartTable()
builder.InsertCell()

' Set the cell formatting
Dim cellFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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(MyDir + "DocumentBuilder.CreateSimpleTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.CreateSimpleTable Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.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

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 + "Aspose.Words.gif");
builder.Writeln();

builder.Write("Image from an internet url, automatically downloaded for you: ");
builder.InsertImage("http://www.aspose.com/Images/aspose-logo.jpg");
builder.Writeln();

builder.Document.Save(MyDir + "Image.CreateFromUrl Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

builder.Write("Image from local file: ")
builder.InsertImage(MyDir & "Aspose.Words.gif")
builder.Writeln()

builder.Write("Image from an internet url, automatically downloaded for you: ")
builder.InsertImage("http://www.aspose.com/Images/aspose-logo.jpg")
builder.Writeln()

builder.Document.Save(MyDir & "Image.CreateFromUrl Out.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

Inserts a paragraph with a top border.

[C#]

DocumentBuilder builder = new DocumentBuilder();

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

builder.Writeln("Hello World!");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim topBorder As Border = builder.ParagraphFormat.Borders(BorderType.Top)
topBorder.Color = System.Drawing.Color.Red
topBorder.LineStyle = LineStyle.DashSmallGap
topBorder.LineWidth = 4

builder.Writeln("Hello World!")
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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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.
VisitCustomXmlMarkupEnd | Called when enumeration of a custom Xml markup node has ended.
VisitCustomXmlMarkupStart | Called when enumeration of a custom Xml markup node has started.
VisitDocumentEnd | Called when enumeration of the document has finished.
VisitDocumentStart | Called when enumeration of the document has started.
VisitDrawingML | Called when a DrawingML node is encountered in the document.
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.
VisitCustomXmlMarkupEnd | Called when enumeration of a custom Xml markup node has ended.
VisitCustomXmlMarkupStart | Called when enumeration of a custom Xml markup node has started.
VisitDocumentEnd | Called when enumeration of the document has finished.
VisitDocumentStart | Called when enumeration of the document has started.
VisitDrawingML | Called when a DrawingML node is encountered in the document.
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.

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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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.

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.

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.

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.

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

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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.

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.

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.

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.

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

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitCustomXmlMarkupEnd Method

Called when enumeration of a custom Xml markup node has ended.

[Visual Basic]
Overridable Public Function VisitCustomXmlMarkupEnd( _
ByVal customXmlMarkup As CustomXmlMarkup _
) As VisitorAction
[C#]
public virtual VisitorAction VisitCustomXmlMarkupEnd(
CustomXmlMarkup customXmlMarkup
);

Parameters

customXmlMarkup
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitCustomXmlMarkupStart Method

Called when enumeration of a custom Xml markup node has started.

[Visual Basic]
Overridable Public Function VisitCustomXmlMarkupStart( _
ByVal customXmlMarkup As CustomXmlMarkup _
) As VisitorAction
[C#]
public virtual VisitorAction VisitCustomXmlMarkupStart(
CustomXmlMarkup customXmlMarkup
);

Parameters

customXmlMarkup
The object that is being visited.

Return Value

A VisitorAction value that specifies how to continue the enumeration.

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.

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.

See Also

DocumentVisitor Class | Aspose.Words Namespace


DocumentVisitor.VisitDrawingML Method

Called when a DrawingML node is encountered in the document.

[Visual Basic]
Overridable Public Function VisitDrawingML( _
ByVal drawingML As DrawingML _
) As VisitorAction
[C#]
public virtual VisitorAction VisitDrawingML(
DrawingML drawingML
);

Parameters

drawingML
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#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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.

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.

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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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.

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

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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.

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.

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.

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

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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.

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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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.

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.

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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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.

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

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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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.

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.

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.

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

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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.

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.

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.

Example

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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.

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.

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.

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

Implements the Visitor Pattern to remove all content formatted as hidden from the document.

[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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

This class provides a static method convert fields of a particular type to static text.

[C#]

public class FieldsHelper : DocumentVisitor
{
    /// <summary>
    /// Converts any fields of the specified type found in the descendants of the node into static text.
    /// </summary>
    /// <param name="compositeNode">The node in which all descendants of the specified FieldType will be converted to static text.</param>
    /// <param name="targetFieldType">The FieldType of the field to convert to static text.</param>
    public static void ConvertFieldsToStaticText(CompositeNode compositeNode, FieldType targetFieldType)
    {
        FieldsHelper helper = new FieldsHelper(targetFieldType);
        compositeNode.Accept(helper);

    }

    private FieldsHelper(FieldType targetFieldType)
    {
        mTargetFieldType = targetFieldType;
    }

    public override VisitorAction VisitFieldStart(FieldStart fieldStart)
    {
        // We must keep track of the starts and ends of fields incase of any nested fields.
        if (fieldStart.FieldType.Equals(mTargetFieldType))
        {
            mFieldDepth++;
            fieldStart.Remove();
        }
        else
        {
            // This removes the field start if it's inside a field that is being converted.
            CheckDepthAndRemoveNode(fieldStart);
        }

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
    {
        // When visiting a field separator we should decrease the depth level.
        if (fieldSeparator.FieldType.Equals(mTargetFieldType))
        {
            mFieldDepth--;
            fieldSeparator.Remove();
        }
        else
        {
            // This removes the field separator if it's inside a field that is being converted.
            CheckDepthAndRemoveNode(fieldSeparator);
        }

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
    {
        if (fieldEnd.FieldType.Equals(mTargetFieldType))
            fieldEnd.Remove();
        else
            CheckDepthAndRemoveNode(fieldEnd); // This removes the field end if it's inside a field that is being converted.

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitRun(Run run)
    {
        // Remove the run if it is between the FieldStart and FieldSeparator of the field being converted.
        CheckDepthAndRemoveNode(run);

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
    {
        if (mFieldDepth > 0)
        {
            // The field code that is being converted continues onto another paragraph. We
            // need to copy the remaining content from this paragraph onto the next paragraph.
            Node nextParagraph = paragraph.NextSibling;

            // Skip ahead to the next available paragraph.
            while (nextParagraph != null && nextParagraph.NodeType != NodeType.Paragraph)
                nextParagraph = nextParagraph.NextSibling;

            // Copy all of the nodes over. Keep a list of these nodes so we know not to remove them.
            while (paragraph.HasChildNodes)
            {
                mNodesToSkip.Add(paragraph.LastChild);
                ((Paragraph)nextParagraph).PrependChild(paragraph.LastChild);
            }

            paragraph.Remove();
        }

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitTableStart(Table table)
    {
        CheckDepthAndRemoveNode(table);

        return VisitorAction.Continue;
    }

    /// <summary>
    /// Checks whether the node is inside a field or should be skipped and then removes it if necessary.
    /// </summary>
    private void CheckDepthAndRemoveNode(Node node)
    {
        if (mFieldDepth > 0 && !mNodesToSkip.Contains(node))
            node.Remove();
    }

    private int mFieldDepth = 0;
    private ArrayList mNodesToSkip = new ArrayList();
    private FieldType mTargetFieldType;
}
[Visual Basic]

Public Class FieldsHelper
    Inherits DocumentVisitor
    ''' <summary>
    ''' Converts any fields of the specified type found in the descendants of the node into static text.
    ''' </summary>
    ''' <param name="compositeNode">The node in which all descendants of the specified FieldType will be converted to static text.</param>
    ''' <param name="targetFieldType">The FieldType of the field to convert to static text.</param>
    Public Shared Sub ConvertFieldsToStaticText(ByVal compositeNode As CompositeNode, ByVal targetFieldType As FieldType)
        Dim helper As New FieldsHelper(targetFieldType)
        compositeNode.Accept(helper)

        Next node
    End Sub

    Private Sub New(ByVal targetFieldType As FieldType)
        mTargetFieldType = targetFieldType
    End Sub

    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' We must keep track of the starts and ends of fields incase of any nested fields.
        If fieldStart.FieldType.Equals(mTargetFieldType) Then
            mFieldDepth += 1
            fieldStart.Remove()
        Else
            ' This removes the field start if it's inside a field that is being converted.
            CheckDepthAndRemoveNode(fieldStart)
        End If

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' When visiting a field separator we should decrease the depth level.
        If fieldSeparator.FieldType.Equals(mTargetFieldType) Then
            mFieldDepth -= 1
            fieldSeparator.Remove()
        Else
            ' This removes the field separator if it's inside a field that is being converted.
            CheckDepthAndRemoveNode(fieldSeparator)
        End If

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If fieldEnd.FieldType.Equals(mTargetFieldType) Then
            fieldEnd.Remove()
        Else
            CheckDepthAndRemoveNode(fieldEnd) ' This removes the field end if it's inside a field that is being converted.
        End If

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        ' Remove the run if it is between the FieldStart and FieldSeparator of the field being converted.
        CheckDepthAndRemoveNode(run)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        If mFieldDepth > 0 Then
            ' The field code that is being converted continues onto another paragraph. We
            ' need to copy the remaining content from this paragraph onto the next paragraph.
            Dim nextParagraph As Node = paragraph.NextSibling

            ' Skip ahead to the next available paragraph.
            Do While nextParagraph IsNot Nothing AndAlso nextParagraph.NodeType <> NodeType.Paragraph
                nextParagraph = nextParagraph.NextSibling
            Loop

            ' Copy all of the nodes over. Keep a list of these nodes so we know not to remove them.
            Do While paragraph.HasChildNodes
                mNodesToSkip.Add(paragraph.LastChild)
                CType(nextParagraph, Paragraph).PrependChild(paragraph.LastChild)
            Loop

            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitTableStart(ByVal table As Table) As VisitorAction
        CheckDepthAndRemoveNode(table)

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Checks whether the node is inside a field or should be skipped and then removes it if necessary.
    ''' </summary>
    Private Sub CheckDepthAndRemoveNode(ByVal node As Node)
        If mFieldDepth > 0 AndAlso (Not mNodesToSkip.Contains(node)) Then
            node.Remove()
        End If
    End Sub

    Private mFieldDepth As Integer = 0
    Private mNodesToSkip As New ArrayList()
    Private mTargetFieldType As FieldType
End Class

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

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.

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;}

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;}

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.

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.

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.

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();

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]
Public Class EditableRangeEnd
Inherits Node
[C#]
public 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.

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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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;}

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;}

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;}

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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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]
Public Class EditableRangeStart
Inherits Node
[C#]
public 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.

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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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;}

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;}

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;}

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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

See Also

EditableRangeStart Class | 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

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


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

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);
[Visual Basic]

Dim info As FileFormatInfo = 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)
Check each file in the folder and move it to the appropriate subfolder.
[C#]

// Loop through all found files.
foreach (string fileName in fileList)
{
    // Extract and display the file name without the path.
    string nameOnly = Path.GetFileName(fileName);
    Console.Write(nameOnly);

    // Check the file format and move the file to the appropriate folder.
    FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);

    // Display the document type.
    switch (info.LoadFormat)
    {
        case LoadFormat.Doc:
            Console.WriteLine("\tMicrosoft Word 97-2003 document.");
            break;
        case LoadFormat.Dot:
            Console.WriteLine("\tMicrosoft Word 97-2003 template.");
            break;
        case LoadFormat.Docx:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document.");
            break;
        case LoadFormat.Docm:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
            break;
        case LoadFormat.Dotx:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template.");
            break;
        case LoadFormat.Dotm:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
            break;
        case LoadFormat.FlatOpc:
            Console.WriteLine("\tFlat OPC document.");
            break;
        case LoadFormat.Rtf:
            Console.WriteLine("\tRTF format.");
            break;
        case LoadFormat.WordML:
            Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
            break;
        case LoadFormat.Html:
            Console.WriteLine("\tHTML format.");
            break;
        case LoadFormat.Mhtml:
            Console.WriteLine("\tMHTML (Web archive) format.");
            break;
        case LoadFormat.Odt:
            Console.WriteLine("\tOpenDocument Text.");
            break;
        case LoadFormat.Ott:
            Console.WriteLine("\tOpenDocument Text Template.");
            break;
        case LoadFormat.DocPreWord97:
            Console.WriteLine("\tMS Word 6 or Word 95 format.");
            break;
        case LoadFormat.Unknown:
        default:
            Console.WriteLine("\tUnknown format.");
            break;
    }

    // Now copy the document into the appropriate folder.
    if (info.IsEncrypted)
    {
        Console.WriteLine("\tAn encrypted document.");
        File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), true);
    }
    else
    {
        switch (info.LoadFormat)
        {
            case LoadFormat.DocPreWord97:
                File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), true);
                break;
            case LoadFormat.Unknown:
                File.Copy(fileName, Path.Combine(unknownDir, nameOnly), true);
                break;
            default:
                File.Copy(fileName, Path.Combine(supportedDir, nameOnly), true);
                break;
        }
    }
}
[Visual Basic]

' Loop through all found files.
For Each fileName As String In fileList
    ' Extract and display the file name without the path.
    Dim nameOnly As String = Path.GetFileName(fileName)
    Console.Write(nameOnly)

    ' Check the file format and move the file to the appropriate folder.
    Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(fileName)

    ' Display the document type.
    Select Case info.LoadFormat
        Case LoadFormat.Doc
            Console.WriteLine(Constants.vbTab & "Microsoft Word 97-2003 document.")
        Case LoadFormat.Dot
            Console.WriteLine(Constants.vbTab & "Microsoft Word 97-2003 template.")
        Case LoadFormat.Docx
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Free Document.")
        Case LoadFormat.Docm
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Enabled Document.")
        Case LoadFormat.Dotx
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Free Template.")
        Case LoadFormat.Dotm
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Enabled Template.")
        Case LoadFormat.FlatOpc
            Console.WriteLine(Constants.vbTab & "Flat OPC document.")
        Case LoadFormat.Rtf
            Console.WriteLine(Constants.vbTab & "RTF format.")
        Case LoadFormat.WordML
            Console.WriteLine(Constants.vbTab & "Microsoft Word 2003 WordprocessingML format.")
        Case LoadFormat.Html
            Console.WriteLine(Constants.vbTab & "HTML format.")
        Case LoadFormat.Mhtml
            Console.WriteLine(Constants.vbTab & "MHTML (Web archive) format.")
        Case LoadFormat.Odt
            Console.WriteLine(Constants.vbTab & "OpenDocument Text.")
        Case LoadFormat.Ott
            Console.WriteLine(Constants.vbTab & "OpenDocument Text Template.")
        Case LoadFormat.DocPreWord97
            Console.WriteLine(Constants.vbTab & "MS Word 6 or Word 95 format.")
        Case Else
            Console.WriteLine(Constants.vbTab & "Unknown format.")
    End Select

    ' Now copy the document into the appropriate folder.
    If info.IsEncrypted Then
        Console.WriteLine(Constants.vbTab & "An encrypted document.")
        File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), True)
    Else
        Select Case info.LoadFormat
            Case LoadFormat.DocPreWord97
                File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), True)
            Case LoadFormat.Unknown
                File.Copy(fileName, Path.Combine(unknownDir, nameOnly), True)
            Case Else
                File.Copy(fileName, Path.Combine(supportedDir, nameOnly), True)
        End Select
    End If
Next fileName

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;}

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);
[Visual Basic]

Dim info As FileFormatInfo = 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(string.Format("Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.", Path.GetFileName(filePath)));
}
[Visual Basic]

' The path to the document which is to be processed.
Dim filePath As String = MyDir & "Document.Signed.docx"

Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(filePath)
If info.HasDigitalSignature Then
    Console.WriteLine(String.Format("Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.", Path.GetFileName(filePath)))
End If

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);
[Visual Basic]

Dim info As FileFormatInfo = 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);
[Visual Basic]

Dim info As FileFormatInfo = 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(MyDir + "Document.WithFileExtension Out" + FileFormatUtil.SaveFormatToExtension(saveFormat));
[Visual Basic]

' 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
Dim docStream As FileStream = File.OpenRead(MyDir & "Document.FileWithoutExtension") ' The file format of this document is actually ".doc"
Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(docStream)

' Retrieve the LoadFormat of the document.
Dim loadFormat As 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.
Dim fileExtension As String = FileFormatUtil.LoadFormatToExtension(loadFormat)
' Now convert this extension into the corresponding SaveFormat enumeration
Dim saveFormat As 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.
Dim doc As New Document(docStream)

' Save the document with the original file name, " Out" and the document's file extension.
doc.Save(MyDir & "Document.WithFileExtension Out" & 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]
Public Class FileFormatUtil
[C#]
public class FileFormatUtil

Example

Check each file in the folder and move it to the appropriate subfolder.

[C#]

// Loop through all found files.
foreach (string fileName in fileList)
{
    // Extract and display the file name without the path.
    string nameOnly = Path.GetFileName(fileName);
    Console.Write(nameOnly);

    // Check the file format and move the file to the appropriate folder.
    FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);

    // Display the document type.
    switch (info.LoadFormat)
    {
        case LoadFormat.Doc:
            Console.WriteLine("\tMicrosoft Word 97-2003 document.");
            break;
        case LoadFormat.Dot:
            Console.WriteLine("\tMicrosoft Word 97-2003 template.");
            break;
        case LoadFormat.Docx:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document.");
            break;
        case LoadFormat.Docm:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
            break;
        case LoadFormat.Dotx:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template.");
            break;
        case LoadFormat.Dotm:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
            break;
        case LoadFormat.FlatOpc:
            Console.WriteLine("\tFlat OPC document.");
            break;
        case LoadFormat.Rtf:
            Console.WriteLine("\tRTF format.");
            break;
        case LoadFormat.WordML:
            Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
            break;
        case LoadFormat.Html:
            Console.WriteLine("\tHTML format.");
            break;
        case LoadFormat.Mhtml:
            Console.WriteLine("\tMHTML (Web archive) format.");
            break;
        case LoadFormat.Odt:
            Console.WriteLine("\tOpenDocument Text.");
            break;
        case LoadFormat.Ott:
            Console.WriteLine("\tOpenDocument Text Template.");
            break;
        case LoadFormat.DocPreWord97:
            Console.WriteLine("\tMS Word 6 or Word 95 format.");
            break;
        case LoadFormat.Unknown:
        default:
            Console.WriteLine("\tUnknown format.");
            break;
    }

    // Now copy the document into the appropriate folder.
    if (info.IsEncrypted)
    {
        Console.WriteLine("\tAn encrypted document.");
        File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), true);
    }
    else
    {
        switch (info.LoadFormat)
        {
            case LoadFormat.DocPreWord97:
                File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), true);
                break;
            case LoadFormat.Unknown:
                File.Copy(fileName, Path.Combine(unknownDir, nameOnly), true);
                break;
            default:
                File.Copy(fileName, Path.Combine(supportedDir, nameOnly), true);
                break;
        }
    }
}
[Visual Basic]

' Loop through all found files.
For Each fileName As String In fileList
    ' Extract and display the file name without the path.
    Dim nameOnly As String = Path.GetFileName(fileName)
    Console.Write(nameOnly)

    ' Check the file format and move the file to the appropriate folder.
    Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(fileName)

    ' Display the document type.
    Select Case info.LoadFormat
        Case LoadFormat.Doc
            Console.WriteLine(Constants.vbTab & "Microsoft Word 97-2003 document.")
        Case LoadFormat.Dot
            Console.WriteLine(Constants.vbTab & "Microsoft Word 97-2003 template.")
        Case LoadFormat.Docx
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Free Document.")
        Case LoadFormat.Docm
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Enabled Document.")
        Case LoadFormat.Dotx
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Free Template.")
        Case LoadFormat.Dotm
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Enabled Template.")
        Case LoadFormat.FlatOpc
            Console.WriteLine(Constants.vbTab & "Flat OPC document.")
        Case LoadFormat.Rtf
            Console.WriteLine(Constants.vbTab & "RTF format.")
        Case LoadFormat.WordML
            Console.WriteLine(Constants.vbTab & "Microsoft Word 2003 WordprocessingML format.")
        Case LoadFormat.Html
            Console.WriteLine(Constants.vbTab & "HTML format.")
        Case LoadFormat.Mhtml
            Console.WriteLine(Constants.vbTab & "MHTML (Web archive) format.")
        Case LoadFormat.Odt
            Console.WriteLine(Constants.vbTab & "OpenDocument Text.")
        Case LoadFormat.Ott
            Console.WriteLine(Constants.vbTab & "OpenDocument Text Template.")
        Case LoadFormat.DocPreWord97
            Console.WriteLine(Constants.vbTab & "MS Word 6 or Word 95 format.")
        Case Else
            Console.WriteLine(Constants.vbTab & "Unknown format.")
    End Select

    ' Now copy the document into the appropriate folder.
    If info.IsEncrypted Then
        Console.WriteLine(Constants.vbTab & "An encrypted document.")
        File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), True)
    Else
        Select Case info.LoadFormat
            Case LoadFormat.DocPreWord97
                File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), True)
            Case LoadFormat.Unknown
                File.Copy(fileName, Path.Combine(unknownDir, nameOnly), True)
            Case Else
                File.Copy(fileName, Path.Combine(supportedDir, nameOnly), True)
        End Select
    End If
Next fileName

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.

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.

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(MyDir + "Document.WithFileExtension Out" + FileFormatUtil.SaveFormatToExtension(saveFormat));
[Visual Basic]

' 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
Dim docStream As FileStream = File.OpenRead(MyDir & "Document.FileWithoutExtension") ' The file format of this document is actually ".doc"
Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(docStream)

' Retrieve the LoadFormat of the document.
Dim loadFormat As 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.
Dim fileExtension As String = FileFormatUtil.LoadFormatToExtension(loadFormat)
' Now convert this extension into the corresponding SaveFormat enumeration
Dim saveFormat As 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.
Dim doc As New Document(docStream)

' Save the document with the original file name, " Out" and the document's file extension.
doc.Save(MyDir & "Document.WithFileExtension Out" & 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);
[Visual Basic]

Dim info As FileFormatInfo = 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(string.Format("Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.", Path.GetFileName(filePath)));
}
[Visual Basic]

' The path to the document which is to be processed.
Dim filePath As String = MyDir & "Document.Signed.docx"

Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(filePath)
If info.HasDigitalSignature Then
    Console.WriteLine(String.Format("Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.", Path.GetFileName(filePath)))
End If
Check each file in the folder and move it to the appropriate subfolder.
[C#]

// Loop through all found files.
foreach (string fileName in fileList)
{
    // Extract and display the file name without the path.
    string nameOnly = Path.GetFileName(fileName);
    Console.Write(nameOnly);

    // Check the file format and move the file to the appropriate folder.
    FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);

    // Display the document type.
    switch (info.LoadFormat)
    {
        case LoadFormat.Doc:
            Console.WriteLine("\tMicrosoft Word 97-2003 document.");
            break;
        case LoadFormat.Dot:
            Console.WriteLine("\tMicrosoft Word 97-2003 template.");
            break;
        case LoadFormat.Docx:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document.");
            break;
        case LoadFormat.Docm:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
            break;
        case LoadFormat.Dotx:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template.");
            break;
        case LoadFormat.Dotm:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
            break;
        case LoadFormat.FlatOpc:
            Console.WriteLine("\tFlat OPC document.");
            break;
        case LoadFormat.Rtf:
            Console.WriteLine("\tRTF format.");
            break;
        case LoadFormat.WordML:
            Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
            break;
        case LoadFormat.Html:
            Console.WriteLine("\tHTML format.");
            break;
        case LoadFormat.Mhtml:
            Console.WriteLine("\tMHTML (Web archive) format.");
            break;
        case LoadFormat.Odt:
            Console.WriteLine("\tOpenDocument Text.");
            break;
        case LoadFormat.Ott:
            Console.WriteLine("\tOpenDocument Text Template.");
            break;
        case LoadFormat.DocPreWord97:
            Console.WriteLine("\tMS Word 6 or Word 95 format.");
            break;
        case LoadFormat.Unknown:
        default:
            Console.WriteLine("\tUnknown format.");
            break;
    }

    // Now copy the document into the appropriate folder.
    if (info.IsEncrypted)
    {
        Console.WriteLine("\tAn encrypted document.");
        File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), true);
    }
    else
    {
        switch (info.LoadFormat)
        {
            case LoadFormat.DocPreWord97:
                File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), true);
                break;
            case LoadFormat.Unknown:
                File.Copy(fileName, Path.Combine(unknownDir, nameOnly), true);
                break;
            default:
                File.Copy(fileName, Path.Combine(supportedDir, nameOnly), true);
                break;
        }
    }
}
[Visual Basic]

' Loop through all found files.
For Each fileName As String In fileList
    ' Extract and display the file name without the path.
    Dim nameOnly As String = Path.GetFileName(fileName)
    Console.Write(nameOnly)

    ' Check the file format and move the file to the appropriate folder.
    Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(fileName)

    ' Display the document type.
    Select Case info.LoadFormat
        Case LoadFormat.Doc
            Console.WriteLine(Constants.vbTab & "Microsoft Word 97-2003 document.")
        Case LoadFormat.Dot
            Console.WriteLine(Constants.vbTab & "Microsoft Word 97-2003 template.")
        Case LoadFormat.Docx
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Free Document.")
        Case LoadFormat.Docm
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Enabled Document.")
        Case LoadFormat.Dotx
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Free Template.")
        Case LoadFormat.Dotm
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Enabled Template.")
        Case LoadFormat.FlatOpc
            Console.WriteLine(Constants.vbTab & "Flat OPC document.")
        Case LoadFormat.Rtf
            Console.WriteLine(Constants.vbTab & "RTF format.")
        Case LoadFormat.WordML
            Console.WriteLine(Constants.vbTab & "Microsoft Word 2003 WordprocessingML format.")
        Case LoadFormat.Html
            Console.WriteLine(Constants.vbTab & "HTML format.")
        Case LoadFormat.Mhtml
            Console.WriteLine(Constants.vbTab & "MHTML (Web archive) format.")
        Case LoadFormat.Odt
            Console.WriteLine(Constants.vbTab & "OpenDocument Text.")
        Case LoadFormat.Ott
            Console.WriteLine(Constants.vbTab & "OpenDocument Text Template.")
        Case LoadFormat.DocPreWord97
            Console.WriteLine(Constants.vbTab & "MS Word 6 or Word 95 format.")
        Case Else
            Console.WriteLine(Constants.vbTab & "Unknown format.")
    End Select

    ' Now copy the document into the appropriate folder.
    If info.IsEncrypted Then
        Console.WriteLine(Constants.vbTab & "An encrypted document.")
        File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), True)
    Else
        Select Case info.LoadFormat
            Case LoadFormat.DocPreWord97
                File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), True)
            Case LoadFormat.Unknown
                File.Copy(fileName, Path.Combine(unknownDir, nameOnly), True)
            Case Else
                File.Copy(fileName, Path.Combine(supportedDir, nameOnly), True)
        End Select
    End If
Next fileName

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(MyDir + "Document.WithFileExtension Out" + FileFormatUtil.SaveFormatToExtension(saveFormat));
[Visual Basic]

' 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
Dim docStream As FileStream = File.OpenRead(MyDir & "Document.FileWithoutExtension") ' The file format of this document is actually ".doc"
Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(docStream)

' Retrieve the LoadFormat of the document.
Dim loadFormat As 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.
Dim fileExtension As String = FileFormatUtil.LoadFormatToExtension(loadFormat)
' Now convert this extension into the corresponding SaveFormat enumeration
Dim saveFormat As 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.
Dim doc As New Document(docStream)

' Save the document with the original file name, " Out" and the document's file extension.
doc.Save(MyDir & "Document.WithFileExtension Out" & 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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

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(MyDir + "Document.WithFileExtension Out" + FileFormatUtil.SaveFormatToExtension(saveFormat));
[Visual Basic]

' 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
Dim docStream As FileStream = File.OpenRead(MyDir & "Document.FileWithoutExtension") ' The file format of this document is actually ".doc"
Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(docStream)

' Retrieve the LoadFormat of the document.
Dim loadFormat As 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.
Dim fileExtension As String = FileFormatUtil.LoadFormatToExtension(loadFormat)
' Now convert this extension into the corresponding SaveFormat enumeration
Dim saveFormat As 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.
Dim doc As New Document(docStream)

' Save the document with the original file name, " Out" and the document's file extension.
doc.Save(MyDir & "Document.WithFileExtension Out" & 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(MyDir + "Document.WithFileExtension Out" + FileFormatUtil.SaveFormatToExtension(saveFormat));
[Visual Basic]

' 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
Dim docStream As FileStream = File.OpenRead(MyDir & "Document.FileWithoutExtension") ' The file format of this document is actually ".doc"
Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(docStream)

' Retrieve the LoadFormat of the document.
Dim loadFormat As 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.
Dim fileExtension As String = FileFormatUtil.LoadFormatToExtension(loadFormat)
' Now convert this extension into the corresponding SaveFormat enumeration
Dim saveFormat As 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.
Dim doc As New Document(docStream)

' Save the document with the original file name, " Out" and the document's file extension.
doc.Save(MyDir & "Document.WithFileExtension Out" & 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(MyDir + "Document.WithFileExtension Out" + FileFormatUtil.SaveFormatToExtension(saveFormat));
[Visual Basic]

' 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
Dim docStream As FileStream = File.OpenRead(MyDir & "Document.FileWithoutExtension") ' The file format of this document is actually ".doc"
Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(docStream)

' Retrieve the LoadFormat of the document.
Dim loadFormat As 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.
Dim fileExtension As String = FileFormatUtil.LoadFormatToExtension(loadFormat)
' Now convert this extension into the corresponding SaveFormat enumeration
Dim saveFormat As 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.
Dim doc As New Document(docStream)

' Save the document with the original file name, " Out" and the document's file extension.
doc.Save(MyDir & "Document.WithFileExtension Out" & 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));
[Visual Basic]

' Define the SaveFormat enumeration to convert.
Dim saveFormat As SaveFormat = SaveFormat.Html
' Convert the SaveFormat enumeration to LoadFormat enumeration.
Dim loadFormat As LoadFormat = FileFormatUtil.SaveFormatToLoadFormat(saveFormat)
Console.WriteLine("The converted LoadFormat is: " & FileFormatUtil.LoadFormatToExtension(loadFormat))

See Also

FileFormatUtil Class | 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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Create a new run of text.
Dim run As New Run(doc, "Hello")

' Specify character formatting for the run of text.
Dim f As Aspose.Words.Font = 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(MyDir + "Lists.ParagraphStyleBulleted Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a paragraph style and specify some formatting for it.
Dim style As 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(MyDir & "Lists.ParagraphStyleBulleted Out.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.
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.
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.

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.
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.
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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

Dim run As 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


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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(MyDir + "Font.Bidi Out.doc");
[Visual Basic]

Dim builder As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025

' Insert some Arabic text.
builder.Writeln("مرحبًا")

builder.Document.Save(MyDir & "Font.Bidi Out.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.");
[Visual Basic]

Dim builder As New DocumentBuilder()

' Specify font formatting before adding text.
Dim font As Aspose.Words.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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(MyDir + "Font.Bidi Out.doc");
[Visual Basic]

Dim builder As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025

' Insert some Arabic text.
builder.Writeln("مرحبًا")

builder.Document.Save(MyDir & "Font.Bidi Out.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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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.");
[Visual Basic]

Dim builder As New DocumentBuilder()

' Specify font formatting before adding text.
Dim font As Aspose.Words.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(MyDir + "DocumentBuilder.InsertHyperlink Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.InsertHyperlink Out.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;}

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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

Dim run As 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;
[Visual Basic]

Dim run As 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;
[Visual Basic]

Dim run As 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;
[Visual Basic]

Dim run As New Run(doc, "Hello")
run.Font.Hidden = True
Implements the Visitor Pattern to remove all content formatted as hidden from the document.
[C#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Create a new run of text.
Dim run As New Run(doc, "Hello")

' Specify character formatting for the run of text.
Dim f As Aspose.Words.Font = 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;
[Visual Basic]

Dim run As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(MyDir + "Font.Bidi Out.doc");
[Visual Basic]

Dim builder As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025

' Insert some Arabic text.
builder.Writeln("مرحبًا")

builder.Document.Save(MyDir & "Font.Bidi Out.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;
[Visual Basic]

Dim run As New Run(doc, "Hello")
run.Font.Kerning = 24

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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx.

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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
run.Font.LocaleId = 1049;
[Visual Basic]

'Create a run of text that contains Russian text.
Dim run As New Run(doc, "Привет")

'Specify the locale so Microsoft Word recognizes this text as Russian.
'For the list of locale identifiers see http://www.microsoft.com/globaldev/reference/lcid-all.mspx
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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx

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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(MyDir + "Font.Bidi Out.doc");
[Visual Basic]

Dim builder As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025

' Insert some Arabic text.
builder.Writeln("مرحبًا")

builder.Document.Save(MyDir & "Font.Bidi Out.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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx

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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdFarEast = 2052;

// Insert some Chinese text.
builder.Writeln("你好世界");

builder.Document.Save(MyDir + "Font.FarEast Out.doc");
[Visual Basic]

Dim builder As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdFarEast = 2052

' Insert some Chinese text.
builder.Writeln("你好世界")

builder.Document.Save(MyDir & "Font.FarEast Out.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.");
[Visual Basic]

Dim builder As New DocumentBuilder()

' Specify font formatting before adding text.
Dim font As Aspose.Words.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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Create a new run of text.
Dim run As New Run(doc, "Hello")

' Specify character formatting for the run of text.
Dim f As Aspose.Words.Font = 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(MyDir + "Font.Names Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "Font.Names Out.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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(MyDir + "Font.Bidi Out.doc");
[Visual Basic]

Dim builder As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025

' Insert some Arabic text.
builder.Writeln("مرحبًا")

builder.Document.Save(MyDir & "Font.Bidi Out.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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdFarEast = 2052;

// Insert some Chinese text.
builder.Writeln("你好世界");

builder.Document.Save(MyDir + "Font.FarEast Out.doc");
[Visual Basic]

Dim builder As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdFarEast = 2052

' Insert some Chinese text.
builder.Writeln("你好世界")

builder.Document.Save(MyDir & "Font.FarEast Out.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(MyDir + "Font.Names Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "Font.Names Out.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;
[Visual Basic]

Dim run As 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;
[Visual Basic]

Dim run As 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 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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

' Add a run of text that is raised 5 points above the baseline.
Dim run As 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 with space between characters reduced by 1pt.
run = new Run(doc, "Condensed by 1pt");
run.Font.Spacing = -1;
para.AppendChild(run);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

' Add a run of text with characters 150% width of normal characters.
Dim run As 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 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.");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim shd As Shading = 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.Engrave = true;
[Visual Basic]

Dim run As New Run(doc, "Hello")
run.Font.Engrave = 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.");
[Visual Basic]

Dim builder As New DocumentBuilder()

' Specify font formatting before adding text.
Dim font As Aspose.Words.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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Create a new run of text.
Dim run As New Run(doc, "Hello")

' Specify character formatting for the run of text.
Dim f As Aspose.Words.Font = 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025;

// Insert some Arabic text.
builder.Writeln("مرحبًا");

builder.Document.Save(MyDir + "Font.Bidi Out.doc");
[Visual Basic]

Dim builder As 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 http://www.microsoft.com/globaldev/reference/lcid-all.mspx
builder.Font.LocaleIdBi = 1025

' Insert some Arabic text.
builder.Writeln("مرحبًا")

builder.Document.Save(MyDir & "Font.Bidi Out.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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

Dim run As 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 with space between characters reduced by 1pt.
run = new Run(doc, "Condensed by 1pt");
run.Font.Spacing = -1;
para.AppendChild(run);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

' Add a run of text with characters 150% width of normal characters.
Dim run As 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 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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

Dim run As 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)
{
    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(MyDir + "Font.Style Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Font.Style.doc")

' Select all run nodes in the document.
Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)

' Loop through every run node.
For Each run As Run In runs
    Dim charStyle As Style = run.Font.Style

    ' If the style of the run is not a built-in character style, apply double underline.
    If (Not charStyle.BuiltIn) Then
        run.Font.Underline = Underline.Double
    End If
Next run

doc.Save(MyDir & "Font.Style Out.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)
{
    // 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(MyDir + "Font.StyleIdentifier Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Font.StyleIdentifier.doc")

' Select all run nodes in the document.
Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)

' Loop through every run node.
For Each run As Run In runs
    ' 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) Then
        run.Font.StyleIdentifier = StyleIdentifier.Strong
    End If
Next run

doc.Save(MyDir & "Font.StyleIdentifier Out.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)
{
    // 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(MyDir + "Font.StyleName Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Font.StyleName.doc")

' Select all run nodes in the document.
Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)

' Loop through every run node.
For Each run As Run In runs
    ' 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") Then
        run.Font.StyleName = "Strong"
    End If
Next run

doc.Save(MyDir & "Font.StyleName Out.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 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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

' Add a run of text that is raised 5 points above the baseline.
Dim run As 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 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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Get the paragraph from the document, we will be adding runs of text to it.
Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)

' Add a run of text that is raised 5 points above the baseline.
Dim run As 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;}

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;
[Visual Basic]

Dim run As 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.");
[Visual Basic]

Dim builder As New DocumentBuilder()

' Specify font formatting before adding text.
Dim font As Aspose.Words.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(MyDir + "DocumentBuilder.InsertHyperlink Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.InsertHyperlink Out.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;
[Visual Basic]

Dim run As 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.

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(MyDir + "DocumentBuilder.InsertHyperlink Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.InsertHyperlink Out.doc")

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 using DocumentBuilder.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text");

builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text")

builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.")
Shows how to add a footnote to a paragraph in the document.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Footnote footnote = new Footnote(doc, FootnoteType.Footnote);
builder.CurrentParagraph.AppendChild(footnote);
footnote.Paragraphs.Add(new Paragraph(doc));
footnote.FirstParagraph.Runs.Add(new Run(doc, "Footnote text."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim footnote As New Footnote(doc, FootnoteType.Footnote)
builder.CurrentParagraph.AppendChild(footnote)
footnote.Paragraphs.Add(New Paragraph(doc))
footnote.FirstParagraph.Runs.Add(New Run(doc, "Footnote text."))

Requirements

Namespace: Aspose.Words

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

See Also

Footnote Members | Aspose.Words Namespace | FootnoteType | InsertFootnote | FootnoteOptions


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.
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.
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.
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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

Footnote Class | Aspose.Words Namespace | FootnoteType | InsertFootnote | FootnoteOptions


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.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Footnote footnote = new Footnote(doc, FootnoteType.Footnote);
builder.CurrentParagraph.AppendChild(footnote);
footnote.Paragraphs.Add(new Paragraph(doc));
footnote.FirstParagraph.Runs.Add(new Run(doc, "Footnote text."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim footnote As New Footnote(doc, FootnoteType.Footnote)
builder.CurrentParagraph.AppendChild(footnote)
footnote.Paragraphs.Add(New Paragraph(doc))
footnote.FirstParagraph.Runs.Add(New Run(doc, "Footnote text."))

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.
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.
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.
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


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;}

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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


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;}

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

Footnote Class | Aspose.Words Namespace | FootnoteType | InsertFootnote | FootnoteOptions


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.

See Also

Footnote Class | Aspose.Words Namespace


FootnoteLocation Enumeration

Defines the footnote or endnote position.

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

Remarks

Members

Member Name | Description | Value
BottomOfPage | Footnotes are output at the bottom of each page. Valid for footnotes only. | 1
BeneathText | Footnotes are output beneath text on each page. Valid for footnotes only. | 2
EndOfSection | Endnotes are output at the end of the section. Valid for endnotes only. | 0
EndOfDocument | Endnotes are output at the end of the document. Valid for endnotes only. | 3

Requirements

Namespace: Aspose.Words

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

See Also

Aspose.Words Namespace | FootnoteOptions


FootnoteNumberingRule Enumeration

Determines when automatic footnote or endnote numbering restarts.

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

Remarks

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


FootnoteOptions Class

Represents the footnote or endnote 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]
Public Class FootnoteOptions
[C#]
public class FootnoteOptions

Remarks

Requirements

Namespace: Aspose.Words

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

See Also

FootnoteOptions Members | Aspose.Words Namespace | FootnoteOptions | EndnoteOptions | FootnoteOptions | EndnoteOptions


FootnoteOptions Members

FootnoteOptions overview

Public Instance Properties

Location | Specifies the footnotes or endnotes position.
NumberStyle | Specifies the number format for automatically numbered footnotes or endnotes.
RestartRule | Determines when automatic numbering restarts.
StartNumber | Specifies the starting number or character for the first automatically numbered footnotes or endnotes.

See Also

FootnoteOptions Class | Aspose.Words Namespace | FootnoteOptions | EndnoteOptions | FootnoteOptions | EndnoteOptions


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

Location | Specifies the footnotes or endnotes position.
NumberStyle | Specifies the number format for automatically numbered footnotes or endnotes.
RestartRule | Determines when automatic numbering restarts.
StartNumber | Specifies the starting number or character for the first automatically numbered footnotes or endnotes.

See Also

FootnoteOptions Class | Aspose.Words Namespace | FootnoteOptions | EndnoteOptions | FootnoteOptions | EndnoteOptions


Location Property

Aspose.Words

FootnoteOptions.Location Property

Specifies the footnotes or endnotes position.

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

Remarks

Not all values are applicable to both footnotes and endnotes. To ascertain which values are applicable see FootnoteLocation.

See Also

FootnoteOptions Class | Aspose.Words Namespace


NumberStyle Property

Aspose.Words

FootnoteOptions.NumberStyle Property

Specifies the number format for automatically numbered footnotes or endnotes.

[Visual Basic]
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.

See Also

FootnoteOptions Class | Aspose.Words Namespace


RestartRule Property

Aspose.Words

FootnoteOptions.RestartRule Property

Determines when automatic numbering restarts.

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

Remarks

Not all values are applicable to both footnotes and endnotes. To ascertain which values are applicable see FootnoteNumberingRule.

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 or endnotes.

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

Remarks

This property has effect only when RestartRule is set to Continuous.

See Also

FootnoteOptions Class | Aspose.Words Namespace


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);
builder.Write("Some text");

builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text")

builder.InsertFootnote(FootnoteType.Footnote, "Footnote text.")
Shows how to add a footnote to a paragraph in the document.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Footnote footnote = new Footnote(doc, FootnoteType.Footnote);
builder.CurrentParagraph.AppendChild(footnote);
footnote.Paragraphs.Add(new Paragraph(doc));
footnote.FirstParagraph.Runs.Add(new Run(doc, "Footnote text."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim footnote As New Footnote(doc, FootnoteType.Footnote)
builder.CurrentParagraph.AppendChild(footnote)
footnote.Paragraphs.Add(New Paragraph(doc))
footnote.FirstParagraph.Runs.Add(New Run(doc, "Footnote text."))

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


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

Creates a footer using the document object model and inserts it into a section.

[C#]

Document doc = new Document();

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

// Add a paragraph with text to the footer.
footer.AppendParagraph("TEST FOOTER");

doc.Save(MyDir + "HeaderFooter.CreateFooter Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim footer As New HeaderFooter(doc, HeaderFooterType.FooterPrimary)
doc.FirstSection.HeadersFooters.Add(footer)

' Add a paragraph with text to the footer.
footer.AppendParagraph("TEST FOOTER")

doc.Save(MyDir & "HeaderFooter.CreateFooter Out.doc")
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];
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", false, false);

doc.Save(MyDir + "HeaderFooter.ReplaceText Out.doc");
[Visual Basic]

' Open the template document, containing obsolete copyright information in the footer.
Dim doc As New Document(MyDir & "HeaderFooter.ReplaceText.doc")

Dim headersFooters As HeaderFooterCollection = doc.FirstSection.HeadersFooters
Dim footer As HeaderFooter = headersFooters(HeaderFooterType.FooterPrimary)
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", False, False)

doc.Save(MyDir & "HeaderFooter.ReplaceText Out.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)
{
    // 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;

    footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    if (footer != null)
        footer.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    if (footer != null)
        footer.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    if (footer != null)
        footer.Remove();
}

doc.Save(MyDir + "HeaderFooter.RemoveFooters Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "HeaderFooter.RemoveFooters.doc")

For Each section As Section In doc
    ' Up to three different footers are possible in a section (for first, even and odd pages).
    ' We check and delete all of them.
    Dim footer As HeaderFooter

    footer = section.HeadersFooters(HeaderFooterType.FooterFirst)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    ' Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters(HeaderFooterType.FooterPrimary)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    footer = section.HeadersFooters(HeaderFooterType.FooterEven)
    If footer IsNot Nothing Then
        footer.Remove()
    End If
Next section

doc.Save(MyDir & "HeaderFooter.RemoveFooters Out.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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 footer using the document object model and inserts it into a section.

[C#]

Document doc = new Document();

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

// Add a paragraph with text to the footer.
footer.AppendParagraph("TEST FOOTER");

doc.Save(MyDir + "HeaderFooter.CreateFooter Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim footer As New HeaderFooter(doc, HeaderFooterType.FooterPrimary)
doc.FirstSection.HeadersFooters.Add(footer)

' Add a paragraph with text to the footer.
footer.AppendParagraph("TEST FOOTER")

doc.Save(MyDir & "HeaderFooter.CreateFooter Out.doc")

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;}

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;}

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.

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.");
        }
    }
}
[Visual Basic]

' Open a document.
Dim doc As New Document(MyDir & "Section.BodyNodeType.doc")

' Get the first section in the document.
Dim section As Section = doc.FirstSection

' A Section is a composite node and therefore can contain child nodes.
' Section can contain only Body and HeaderFooter nodes.
For Each node As Node In section
    ' Every node has the NodeType property.
    Select Case node.NodeType
        Case NodeType.Body
            ' If the node type is Body, we can cast the node to the Body class.
            Dim body As Body = CType(node, Body)

            ' Write the content of the main story of the section to the console.
            Console.WriteLine("*** Body ***")
            Console.WriteLine(body.GetText())
            Exit Select
        Case NodeType.HeaderFooter
            ' If the node type is HeaderFooter, we can cast the node to the HeaderFooter class.
            Dim headerFooter As HeaderFooter = CType(node, HeaderFooter)

            ' Write the content of the header footer to the console.
            Console.WriteLine("*** HeaderFooter ***")
            Console.WriteLine(headerFooter.HeaderFooterType)
            Console.WriteLine(headerFooter.GetText())
            Exit Select
        Case Else
            ' Other types of nodes never occur inside a Section node.
            Throw New Exception("Unexpected node type in a section.")
    End Select
Next node

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.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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 footer using the document object model and inserts it into a section.

[C#]

Document doc = new Document();

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

// Add a paragraph with text to the footer.
footer.AppendParagraph("TEST FOOTER");

doc.Save(MyDir + "HeaderFooter.CreateFooter Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim footer As New HeaderFooter(doc, HeaderFooterType.FooterPrimary)
doc.FirstSection.HeadersFooters.Add(footer)

' Add a paragraph with text to the footer.
footer.AppendParagraph("TEST FOOTER")

doc.Save(MyDir & "HeaderFooter.CreateFooter Out.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)
{
    // 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;

    footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    if (footer != null)
        footer.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    if (footer != null)
        footer.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    if (footer != null)
        footer.Remove();
}

doc.Save(MyDir + "HeaderFooter.RemoveFooters Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "HeaderFooter.RemoveFooters.doc")

For Each section As Section In doc
    ' Up to three different footers are possible in a section (for first, even and odd pages).
    ' We check and delete all of them.
    Dim footer As HeaderFooter

    footer = section.HeadersFooters(HeaderFooterType.FooterFirst)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    ' Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters(HeaderFooterType.FooterPrimary)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    footer = section.HeadersFooters(HeaderFooterType.FooterEven)
    If footer IsNot Nothing Then
        footer.Remove()
    End If
Next section

doc.Save(MyDir & "HeaderFooter.RemoveFooters Out.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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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];
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", false, false);

doc.Save(MyDir + "HeaderFooter.ReplaceText Out.doc");
[Visual Basic]

' Open the template document, containing obsolete copyright information in the footer.
Dim doc As New Document(MyDir & "HeaderFooter.ReplaceText.doc")

Dim headersFooters As HeaderFooterCollection = doc.FirstSection.HeadersFooters
Dim footer As HeaderFooter = headersFooters(HeaderFooterType.FooterPrimary)
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", False, False)

doc.Save(MyDir & "HeaderFooter.ReplaceText Out.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)
{
    // 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;

    footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    if (footer != null)
        footer.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    if (footer != null)
        footer.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    if (footer != null)
        footer.Remove();
}

doc.Save(MyDir + "HeaderFooter.RemoveFooters Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "HeaderFooter.RemoveFooters.doc")

For Each section As Section In doc
    ' Up to three different footers are possible in a section (for first, even and odd pages).
    ' We check and delete all of them.
    Dim footer As HeaderFooter

    footer = section.HeadersFooters(HeaderFooterType.FooterFirst)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    ' Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters(HeaderFooterType.FooterPrimary)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    footer = section.HeadersFooters(HeaderFooterType.FooterEven)
    If footer IsNot Nothing Then
        footer.Remove()
    End If
Next section

doc.Save(MyDir & "HeaderFooter.RemoveFooters Out.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.

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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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.

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 append a document to another document and continue headers and footers from the destination document.

[C#]

Document dstDoc = new Document(gDataDir + "TestFile.Destination.doc");
Document srcDoc =  new Document(gDataDir + "TestFile.Source.doc");

// Set the appended document to appear on a new page.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;

// Link the headers and footers in the source document to the previous section.
// This will override any headers or footers already found in the source document.
srcDoc.FirstSection.HeadersFooters.LinkToPrevious(true);

dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
dstDoc.Save(gDataDir + "TestFile.LinkHeadersFooters Out.doc");
[Visual Basic]

Dim dstDoc As New Document(gDataDir & "TestFile.Destination.doc")
Dim srcDoc As New Document(gDataDir & "TestFile.Source.doc")

' Set the appended document to appear on a new page.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage

' Link the headers and footers in the source document to the previous section.
' This will override any headers or footers already found in the source document.
srcDoc.FirstSection.HeadersFooters.LinkToPrevious(True)

dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting)
dstDoc.Save(gDataDir & "TestFile.LinkHeadersFooters Out.doc")

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.

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)
{
    // 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;

    footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    if (footer != null)
        footer.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    if (footer != null)
        footer.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    if (footer != null)
        footer.Remove();
}

doc.Save(MyDir + "HeaderFooter.RemoveFooters Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "HeaderFooter.RemoveFooters.doc")

For Each section As Section In doc
    ' Up to three different footers are possible in a section (for first, even and odd pages).
    ' We check and delete all of them.
    Dim footer As HeaderFooter

    footer = section.HeadersFooters(HeaderFooterType.FooterFirst)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    ' Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters(HeaderFooterType.FooterPrimary)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    footer = section.HeadersFooters(HeaderFooterType.FooterEven)
    If footer IsNot Nothing Then
        footer.Remove()
    End If
Next section

doc.Save(MyDir & "HeaderFooter.RemoveFooters Out.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(MyDir + "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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(MyDir + "DocumentBuilder.InsertWatermark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)

Dim image As Image = Image.FromFile(MyDir & "Watermark.png")

' Insert a floating picture.
Dim shape As 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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2

doc.Save(MyDir & "DocumentBuilder.InsertWatermark Out.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(MyDir + "DocumentBuilder.HeadersAndFooters Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.HeadersAndFooters Out.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


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.

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.

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


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
);

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.

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.

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.

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.

Example

Shows how to manually append the content from one document to the end of another document.

[C#]

/// <summary>
/// A manual implementation of the Document.AppendDocument function which shows the general
/// steps of how a document is appended to another.
/// </summary>
/// <param name="dstDoc">The destination document where to append to.</param>
/// <param name="srcDoc">The source document.</param>
/// <param name="mode">The import mode to use when importing content from another document.</param>
public void AppendDocument(Document dstDoc, Document srcDoc, ImportFormatMode mode)
{
    // Loop through all sections in the source document.
    // Section nodes are immediate children of the Document node so we can just enumerate the Document.
    foreach (Section srcSection in srcDoc)
    {
        // Because we are copying a section from one document to another,
        // it is required to import the Section node into the destination document.
        // This adjusts any document-specific references to styles, lists, etc.
        //
        // Importing a node creates a copy of the original node, but the copy
        // is ready to be inserted into the destination document.
        Node dstSection = dstDoc.ImportNode(srcSection, true, mode);

        // Now the new section node can be appended to the destination document.
        dstDoc.AppendChild(dstSection);
    }
}
[Visual Basic]

''' <summary>
''' A manual implementation of the Document.AppendDocument function which shows the general
''' steps of how a document is appended to another.
''' </summary>
''' <param name="dstDoc">The destination document where to append to.</param>
''' <param name="srcDoc">The source document.</param>
''' <param name="mode">The import mode to use when importing content from another document.</param>
Public Sub AppendDocument(ByVal dstDoc As Document, ByVal srcDoc As Document, ByVal mode As ImportFormatMode)
    ' Loop through all sections in the source document.
    ' Section nodes are immediate children of the Document node so we can just enumerate the Document.
    For Each srcSection As Section In srcDoc
        ' Because we are copying a section from one document to another,
        ' it is required to import the Section node into the destination document.
        ' This adjusts any document-specific references to styles, lists, etc.
        '
        ' Importing a node creates a copy of the original node, but the copy
        ' is ready to be inserted into the destination document.
        Dim dstSection As Node = dstDoc.ImportNode(srcSection, True, mode)

        ' Now the new section node can be appended to the destination document.
        dstDoc.AppendChild(dstSection)
    Next srcSection
End Sub
Shows how to manually prepend the content from one document to the beginning of another document.
[C#]

public static void PrependDocumentMain()
{
    Document dstDoc = new Document(gDataDir + "TestFile.Destination.doc");
    Document srcDoc = new Document(gDataDir + "TestFile.Source.doc");

    // Append the source document to the destination document. This causes the result to have line spacing problems.
    dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);

    // Instead prepend the content of the destination document to the start of the source document.
    // This results in the same joined document but with no line spacing issues.
    PrependDocument(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting);
}

/// <summary>
/// A modified version of the AppendDocument method which prepends the content of one document to the start
/// of another.
/// </summary>
/// <param name="dstDoc">The destination document where to prepend the source document to.</param>
/// <param name="srcDoc">The source document.</param>
public static void PrependDocument(Document dstDoc, Document srcDoc, ImportFormatMode mode)
{
    // Loop through all sections in the source document.
    // Section nodes are immediate children of the Document node so we can just enumerate the Document.
    ArrayList sections = new ArrayList(srcDoc.Sections.ToArray());

    // Reverse the order of the sections so they are prepended to start of the destination document in the correct order.
    sections.Reverse();

    foreach (Section srcSection in sections)
    {
        // Import the nodes from the source document.
        Node dstSection = dstDoc.ImportNode(srcSection, true, mode);

        // Now the new section node can be prepended to the destination document.
        // Note how PrependChild is used instead of AppendChild. This is the only line changed compared
        // to the original method.
        dstDoc.PrependChild(dstSection);
    }
}
[Visual Basic]

Public Shared Sub PrependDocumentMain()
    Dim dstDoc As New Document(gDataDir & "TestFile.Destination.doc")
    Dim srcDoc As New Document(gDataDir & "TestFile.Source.doc")

    ' Append the source document to the destination document. This causes the result to have line spacing problems.
    dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting)

    ' Instead prepend the content of the destination document to the start of the source document.
    ' This results in the same joined document but with no line spacing issues.
    PrependDocument(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting)
End Sub

''' <summary>
''' A modified version of the AppendDocument method which prepends the content of one document to the start
''' of another.
''' </summary>
''' <param name="dstDoc">The destination document where to prepend the source document to.</param>
''' <param name="srcDoc">The source document.</param>
Public Shared Sub PrependDocument(ByVal dstDoc As Document, ByVal srcDoc As Document, ByVal mode As ImportFormatMode)
    ' Loop through all sections in the source document.
    ' Section nodes are immediate children of the Document node so we can just enumerate the Document.
    Dim sections As New ArrayList(srcDoc.Sections.ToArray())

    ' Reverse the order of the sections so they are prepended to start of the destination document in the correct order.
    sections.Reverse()

    For Each srcSection As Section In sections
        ' Import the nodes from the source document.
        Dim dstSection As Node = dstDoc.ImportNode(srcSection, True, mode)

        ' Now the new section node can be prepended to the destination document.
        ' Note how PrependChild is used instead of AppendChild. This is the only line changed compared
        ' to the original method.
        dstDoc.PrependChild(dstSection)
    Next srcSection
End Sub

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

Requirements

Namespace: Aspose.Words

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

See Also

Aspose.Words Namespace | ImportNode


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.Drawing.DrawingML
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.

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.
IsInsertRevision | Returns true if this object was 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
IsInsertRevision | Returns true if this object was 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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;}

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;}

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;}

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 footnote to a paragraph in the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Footnote footnote = new Footnote(doc, FootnoteType.Footnote);
builder.CurrentParagraph.AppendChild(footnote);
footnote.Paragraphs.Add(new Paragraph(doc));
footnote.FirstParagraph.Runs.Add(new Run(doc, "Footnote text."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim footnote As New Footnote(doc, FootnoteType.Footnote)
builder.CurrentParagraph.AppendChild(footnote)
footnote.Paragraphs.Add(New Paragraph(doc))
footnote.FirstParagraph.Runs.Add(New Run(doc, "Footnote text."))
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."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim comment As 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."))

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.
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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
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 footnote to a paragraph in the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Footnote footnote = new Footnote(doc, FootnoteType.Footnote);
builder.CurrentParagraph.AppendChild(footnote);
footnote.Paragraphs.Add(new Paragraph(doc));
footnote.FirstParagraph.Runs.Add(new Run(doc, "Footnote text."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim footnote As New Footnote(doc, FootnoteType.Footnote)
builder.CurrentParagraph.AppendChild(footnote)
footnote.Paragraphs.Add(New Paragraph(doc))
footnote.FirstParagraph.Runs.Add(New Run(doc, "Footnote text."))
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."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim comment As 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

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;}

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;}

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;}

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;}

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 footnote to a paragraph in the document.

[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");

Footnote footnote = new Footnote(doc, FootnoteType.Footnote);
builder.CurrentParagraph.AppendChild(footnote);
footnote.Paragraphs.Add(new Paragraph(doc));
footnote.FirstParagraph.Runs.Add(new Run(doc, "Footnote text."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim footnote As New Footnote(doc, FootnoteType.Footnote)
builder.CurrentParagraph.AppendChild(footnote)
footnote.Paragraphs.Add(New Paragraph(doc))
footnote.FirstParagraph.Runs.Add(New Run(doc, "Footnote text."))
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."));
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)
builder.Write("Some text is added.")

Dim comment As 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

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;}

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;}

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;}

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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();

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 HandleNodeChanging_FontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(MyDir + "Document.FontChanger Out.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 HandleNodeChanging_FontChanger : 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
    }
}
[Visual Basic]

Public Sub TestNodeChangingInDocument()
    ' Create a blank document object
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    ' Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = New HandleNodeChanging_FontChanger()

    ' Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>")

    doc.Save(MyDir & "Document.FontChanger Out.doc")

    ' Check that the inserted content has the correct formatting
    Dim run As Run = CType(doc.GetChild(NodeType.Run, 0, True), Run)
    Assert.AreEqual(24.0, run.Font.Size)
    Assert.AreEqual("Arial", run.Font.Name)
End Sub

Public Class HandleNodeChanging_FontChanger
    Implements INodeChangingCallback
    ' Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    Private Sub NodeInserted(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserted
        ' Change the font of inserted text contained in the Run nodes.
        If args.Node.NodeType = NodeType.Run Then
            Dim font As Aspose.Words.Font = (CType(args.Node, Run)).Font
            font.Size = 24
            font.Name = "Arial"
        End If
    End Sub

    Private Sub NodeInserting(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserting
        ' Do Nothing
    End Sub

    Private Sub NodeRemoved(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoved
        ' Do Nothing
    End Sub

    Private Sub NodeRemoving(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoving
        ' Do Nothing
    End Sub
End Class

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 HandleNodeChanging_FontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(MyDir + "Document.FontChanger Out.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 HandleNodeChanging_FontChanger : 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
    }
}
[Visual Basic]

Public Sub TestNodeChangingInDocument()
    ' Create a blank document object
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    ' Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = New HandleNodeChanging_FontChanger()

    ' Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>")

    doc.Save(MyDir & "Document.FontChanger Out.doc")

    ' Check that the inserted content has the correct formatting
    Dim run As Run = CType(doc.GetChild(NodeType.Run, 0, True), Run)
    Assert.AreEqual(24.0, run.Font.Size)
    Assert.AreEqual("Arial", run.Font.Name)
End Sub

Public Class HandleNodeChanging_FontChanger
    Implements INodeChangingCallback
    ' Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    Private Sub NodeInserted(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserted
        ' Change the font of inserted text contained in the Run nodes.
        If args.Node.NodeType = NodeType.Run Then
            Dim font As Aspose.Words.Font = (CType(args.Node, Run)).Font
            font.Size = 24
            font.Name = "Arial"
        End If
    End Sub

    Private Sub NodeInserting(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserting
        ' Do Nothing
    End Sub

    Private Sub NodeRemoved(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoved
        ' Do Nothing
    End Sub

    Private Sub NodeRemoving(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoving
        ' Do Nothing
    End Sub
End Class

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 HandleNodeChanging_FontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(MyDir + "Document.FontChanger Out.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 HandleNodeChanging_FontChanger : 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
    }
}
[Visual Basic]

Public Sub TestNodeChangingInDocument()
    ' Create a blank document object
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    ' Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = New HandleNodeChanging_FontChanger()

    ' Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>")

    doc.Save(MyDir & "Document.FontChanger Out.doc")

    ' Check that the inserted content has the correct formatting
    Dim run As Run = CType(doc.GetChild(NodeType.Run, 0, True), Run)
    Assert.AreEqual(24.0, run.Font.Size)
    Assert.AreEqual("Arial", run.Font.Name)
End Sub

Public Class HandleNodeChanging_FontChanger
    Implements INodeChangingCallback
    ' Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    Private Sub NodeInserted(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserted
        ' Change the font of inserted text contained in the Run nodes.
        If args.Node.NodeType = NodeType.Run Then
            Dim font As Aspose.Words.Font = (CType(args.Node, Run)).Font
            font.Size = 24
            font.Name = "Arial"
        End If
    End Sub

    Private Sub NodeInserting(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserting
        ' Do Nothing
    End Sub

    Private Sub NodeRemoved(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoved
        ' Do Nothing
    End Sub

    Private Sub NodeRemoving(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoving
        ' Do Nothing
    End Sub
End Class

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 HandleNodeChanging_FontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(MyDir + "Document.FontChanger Out.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 HandleNodeChanging_FontChanger : 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
    }
}
[Visual Basic]

Public Sub TestNodeChangingInDocument()
    ' Create a blank document object
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    ' Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = New HandleNodeChanging_FontChanger()

    ' Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>")

    doc.Save(MyDir & "Document.FontChanger Out.doc")

    ' Check that the inserted content has the correct formatting
    Dim run As Run = CType(doc.GetChild(NodeType.Run, 0, True), Run)
    Assert.AreEqual(24.0, run.Font.Size)
    Assert.AreEqual("Arial", run.Font.Name)
End Sub

Public Class HandleNodeChanging_FontChanger
    Implements INodeChangingCallback
    ' Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    Private Sub NodeInserted(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserted
        ' Change the font of inserted text contained in the Run nodes.
        If args.Node.NodeType = NodeType.Run Then
            Dim font As Aspose.Words.Font = (CType(args.Node, Run)).Font
            font.Size = 24
            font.Name = "Arial"
        End If
    End Sub

    Private Sub NodeInserting(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserting
        ' Do Nothing
    End Sub

    Private Sub NodeRemoved(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoved
        ' Do Nothing
    End Sub

    Private Sub NodeRemoving(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoving
        ' Do Nothing
    End Sub
End Class

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 HandleNodeChanging_FontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(MyDir + "Document.FontChanger Out.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 HandleNodeChanging_FontChanger : 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
    }
}
[Visual Basic]

Public Sub TestNodeChangingInDocument()
    ' Create a blank document object
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    ' Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = New HandleNodeChanging_FontChanger()

    ' Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>")

    doc.Save(MyDir & "Document.FontChanger Out.doc")

    ' Check that the inserted content has the correct formatting
    Dim run As Run = CType(doc.GetChild(NodeType.Run, 0, True), Run)
    Assert.AreEqual(24.0, run.Font.Size)
    Assert.AreEqual("Arial", run.Font.Name)
End Sub

Public Class HandleNodeChanging_FontChanger
    Implements INodeChangingCallback
    ' Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    Private Sub NodeInserted(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserted
        ' Change the font of inserted text contained in the Run nodes.
        If args.Node.NodeType = NodeType.Run Then
            Dim font As Aspose.Words.Font = (CType(args.Node, Run)).Font
            font.Size = 24
            font.Name = "Arial"
        End If
    End Sub

    Private Sub NodeInserting(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserting
        ' Do Nothing
    End Sub

    Private Sub NodeRemoved(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoved
        ' Do Nothing
    End Sub

    Private Sub NodeRemoving(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoving
        ' Do Nothing
    End Sub
End Class

See Also

INodeChangingCallback Interface | 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

Aspose.Words throws a ThreadInterruptedException on processing the interrupt request.

See Also

InterruptionToken Class | Aspose.Words 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#]

public void InsertDocumentAtReplace()
{
    Document mainDoc = new Document(MyDir + "InsertDocument1.doc");
    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false);
    mainDoc.Save(MyDir + "InsertDocumentAtReplace Out.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph)e.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
[Visual Basic]

Public Sub InsertDocumentAtReplace()
    Dim mainDoc As New Document(MyDir & "InsertDocument1.doc")
    mainDoc.Range.Replace(New Regex("\[MY_DOCUMENT\]"), New InsertDocumentAtReplaceHandler(), False)
    mainDoc.Save(MyDir & "InsertDocumentAtReplace Out.doc")
End Sub

Private Class InsertDocumentAtReplaceHandler
    Implements IReplacingCallback
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim subDoc As New Document(MyDir & "InsertDocument2.doc")

        ' Insert a document after the paragraph, containing the match text.
        Dim para As Paragraph = CType(e.MatchNode.ParentNode, Paragraph)
        InsertDocument(para, subDoc)

        ' Remove the paragraph with the match text.
        para.Remove()

        Return ReplaceAction.Skip
    End Function
End Class
Replaces text specified with regular expression with HTML.
[C#]

public void ReplaceWithInsertHtml()
{
    // Open the document.
    Document doc = new Document(MyDir + "Range.ReplaceWithInsertHtml.doc");

    doc.Range.Replace(new Regex(@"<CustomerName>"), new ReplaceWithHtmlEvaluator(), false);

    // Save the modified document.
    doc.Save(MyDir + "Range.ReplaceWithInsertHtml Out.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    /// <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 e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>");

        e.Replacement = "";
        return ReplaceAction.Replace;
    }
}
[Visual Basic]

Public Sub ReplaceWithInsertHtml()
    ' Open the document.
    Dim doc As New Document(MyDir & "Range.ReplaceWithInsertHtml.doc")

    doc.Range.Replace(New Regex("<CustomerName>"), New ReplaceWithHtmlEvaluator(), False)

    ' Save the modified document.
    doc.Save(MyDir & "Range.ReplaceWithInsertHtml Out.doc")

End Sub

Private Class ReplaceWithHtmlEvaluator
    Implements IReplacingCallback
    ''' <summary>
    ''' NOTE: This is a simplistic method that will only work well when the match
    ''' starts at the beginning of a run.
    ''' </summary>
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim builder As New DocumentBuilder(CType(e.MatchNode.Document, Document))
        builder.MoveTo(e.MatchNode)
        ' Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>")

        e.Replacement = ""
        Return ReplaceAction.Replace
    End Function
End Class

Requirements

Namespace: Aspose.Words

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

See Also

IReplacingCallback Members | Aspose.Words 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 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 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#]

public void InsertDocumentAtReplace()
{
    Document mainDoc = new Document(MyDir + "InsertDocument1.doc");
    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false);
    mainDoc.Save(MyDir + "InsertDocumentAtReplace Out.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph)e.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
[Visual Basic]

Public Sub InsertDocumentAtReplace()
    Dim mainDoc As New Document(MyDir & "InsertDocument1.doc")
    mainDoc.Range.Replace(New Regex("\[MY_DOCUMENT\]"), New InsertDocumentAtReplaceHandler(), False)
    mainDoc.Save(MyDir & "InsertDocumentAtReplace Out.doc")
End Sub

Private Class InsertDocumentAtReplaceHandler
    Implements IReplacingCallback
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim subDoc As New Document(MyDir & "InsertDocument2.doc")

        ' Insert a document after the paragraph, containing the match text.
        Dim para As Paragraph = CType(e.MatchNode.ParentNode, Paragraph)
        InsertDocument(para, subDoc)

        ' Remove the paragraph with the match text.
        para.Remove()

        Return ReplaceAction.Skip
    End Function
End Class
Replaces text specified with regular expression with HTML.
[C#]

public void ReplaceWithInsertHtml()
{
    // Open the document.
    Document doc = new Document(MyDir + "Range.ReplaceWithInsertHtml.doc");

    doc.Range.Replace(new Regex(@"<CustomerName>"), new ReplaceWithHtmlEvaluator(), false);

    // Save the modified document.
    doc.Save(MyDir + "Range.ReplaceWithInsertHtml Out.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    /// <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 e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>");

        e.Replacement = "";
        return ReplaceAction.Replace;
    }
}
[Visual Basic]

Public Sub ReplaceWithInsertHtml()
    ' Open the document.
    Dim doc As New Document(MyDir & "Range.ReplaceWithInsertHtml.doc")

    doc.Range.Replace(New Regex("<CustomerName>"), New ReplaceWithHtmlEvaluator(), False)

    ' Save the modified document.
    doc.Save(MyDir & "Range.ReplaceWithInsertHtml Out.doc")

End Sub

Private Class ReplaceWithHtmlEvaluator
    Implements IReplacingCallback
    ''' <summary>
    ''' NOTE: This is a simplistic method that will only work well when the match
    ''' starts at the beginning of a run.
    ''' </summary>
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim builder As New DocumentBuilder(CType(e.MatchNode.Document, Document))
        builder.MoveTo(e.MatchNode)
        ' Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>")

        e.Replacement = ""
        Return ReplaceAction.Replace
    End Function
End Class

See Also

IReplacingCallback Interface | 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

Demonstrates 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 procssing. 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);
        }
    }

}
[Visual Basic]

Public Class HandleDocumentWarnings
    Implements IWarningCallback
    ''' <summary>
    ''' Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    ''' potential issue during document procssing. The callback can be set to listen for warnings generated during document
    ''' load and/or document save.
    ''' </summary>
    Public Sub Warning(ByVal info As WarningInfo) Implements IWarningCallback.Warning
        ' We are only interested in fonts being substituted.
        If info.WarningType = WarningType.FontSubstitution Then
            Console.WriteLine("Font substitution: " & info.Description)
        End If
    End Sub

End Class
Demonstrates how to recieve notifications of font substitutions by using IWarningCallback.
[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Document.doc");

// We can choose the default font to use in the case of any missing fonts.
FontSettings.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 subsuited with the default
// font specified under FontSettings.DefaultFontName. We can pick up on this subsuition using our callback.
FontSettings.SetFontsFolder(string.Empty, false);

// Create a new class implementing IWarningCallback which collect any warnings produced during document save.
HandleDocumentWarnings callback = new HandleDocumentWarnings();

// We assign the callback to the appropriate save options class. In this case, we are going to save to PDF
// so we create a PdfSaveOptions class and assign the callback there.
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.WarningCallback = callback;

// Pass the save options along with the save path to the save method.
doc.Save(MyDir + "Rendering.MissingFontNotification Out.pdf", saveOptions);
[Visual Basic]

' Load the document to render.
Dim doc As New Document(MyDir & "Document.doc")

' We can choose the default font to use in the case of any missing fonts.
FontSettings.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 subsuited with the default
' font specified under FontSettings.DefaultFontName. We can pick up on this subsuition using our callback.
FontSettings.SetFontsFolder(String.Empty, False)

' Create a new class implementing IWarningCallback which collect any warnings produced during document save.
Dim callback As New HandleDocumentWarnings()

' We assign the callback to the appropriate save options class. In this case, we are going to save to PDF
' so we create a PdfSaveOptions class and assign the callback there.
Dim saveOptions As New PdfSaveOptions()
saveOptions.WarningCallback = callback

' Pass the save options along with the save path to the save method.
doc.Save(MyDir & "Rendering.MissingFontNotification Out.pdf", saveOptions)

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
);

See Also

IWarningCallback Interface | 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

In this example Aspose.Words will attempt to find the license file in the embedded resources or in the assembly folders.

[C#]

Aspose.Words.License license = new Aspose.Words.License();
license.SetLicense("Aspose.Words.lic");
[Visual Basic]

Dim license As New Aspose.Words.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 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

In this example Aspose.Words will attempt to find the license file in the embedded resources or in the assembly folders.

[C#]

Aspose.Words.License license = new Aspose.Words.License();
license.SetLicense("Aspose.Words.lic");
[Visual Basic]

Dim license As New Aspose.Words.License()
license.SetLicense("Aspose.Words.lic")

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#]

Aspose.Words.License license = new Aspose.Words.License();
license.SetLicense(myStream);
[Visual Basic]

Dim license As New Aspose.Words.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

In this example Aspose.Words will attempt to find the license file in the embedded resources or in the assembly folders.

[C#]

Aspose.Words.License license = new Aspose.Words.License();
license.SetLicense("Aspose.Words.lic");
[Visual Basic]

Dim license As New Aspose.Words.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;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(MyDir + "PageSetup.LineNumbers Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.LineStartingNumber = 1
ps.LineNumberCountBy = 5
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage

For i As Integer = 1 To 20
    builder.Writeln(String.Format("Line {0}.", i))
Next i

builder.Document.Save(MyDir & "PageSetup.LineNumbers Out.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 = System.Drawing.Color.Green;
builder.Font.Border.LineWidth = 2.5;
builder.Font.Border.LineStyle = LineStyle.DashDotStroker;

builder.Write("run of text in a green border");
[Visual Basic]

Dim builder As New DocumentBuilder()

builder.Font.Border.Color = System.Drawing.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(MyDir + "Lists.SpecifyListLevel Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next i

' This is a way to stop list formatting.
builder.ListFormat.List = Nothing

builder.Document.Save(MyDir & "Lists.SpecifyListLevel Out.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)
{
    if (para.ListFormat.IsListItem)
    {
        Console.WriteLine(string.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId));
        Console.WriteLine(para.GetText());
    }
}
[Visual Basic]

Dim paras As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
For Each para As Paragraph In paras
    If para.ListFormat.IsListItem Then
        Console.WriteLine(String.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId))
        Console.WriteLine(para.GetText())
    End If
Next para

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;
Aspose.Words.Lists.List list = doc.Lists[0];
foreach (Paragraph paragraph in body.Paragraphs)
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 2;
}
[Visual Basic]

Dim body As Body = doc.FirstSection.Body
Dim list As Aspose.Words.Lists.List = doc.Lists(0)
For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.List = list
    paragraph.ListFormat.ListLevelNumber = 2
Next paragraph
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(MyDir + "Lists.SpecifyListLevel Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next i

' This is a way to stop list formatting.
builder.ListFormat.List = Nothing

builder.Document.Save(MyDir & "Lists.SpecifyListLevel Out.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.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(MyDir + "Lists.RestartNumberingUsingListCopy Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a list based on a template.
Dim list1 As Aspose.Words.Lists.List = 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.
Dim list2 As Aspose.Words.Lists.List = 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(MyDir & "Lists.RestartNumberingUsingListCopy Out.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List numberedList = doc.Lists.Add(ListTemplate.NumberDefault);
builder.ListFormat.List = numberedList;
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;
builder.Writeln("Numebered list item 1.");

// Create a bulleted list.
Aspose.Words.Lists.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(MyDir + "Lists.NestedLists Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create an outline list for the headings.
Dim outlineList As Aspose.Words.Lists.List = 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.
Dim numberedList As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)
builder.ListFormat.List = numberedList
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal
builder.Writeln("Numebered list item 1.")

' Create a bulleted list.
Dim bulletedList As Aspose.Words.Lists.List = 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(MyDir & "Lists.NestedLists Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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;
Aspose.Words.Lists.List list = doc.Lists[0];
foreach (Paragraph paragraph in body.Paragraphs)
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 2;
}
[Visual Basic]

Dim body As Body = doc.FirstSection.Body
Dim list As Aspose.Words.Lists.List = doc.Lists(0)
For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.List = list
    paragraph.ListFormat.ListLevelNumber = 2
Next paragraph
Creates new list formatting and applies it to a collection of paragraphs.
[C#]

Aspose.Words.Lists.List list = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot);

Body body = doc.FirstSection.Body;
foreach (Paragraph paragraph in body.Paragraphs)
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 1;
}
[Visual Basic]

Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot)

Dim body As Body = doc.FirstSection.Body
For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.List = list
    paragraph.ListFormat.ListLevelNumber = 1
Next paragraph
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(MyDir + "Lists.SpecifyListLevel Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next i

' This is a way to stop list formatting.
builder.ListFormat.List = Nothing

builder.Document.Save(MyDir & "Lists.SpecifyListLevel Out.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(MyDir + "Lists.ApplyDefaultBulletsAndNumbers Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "Lists.ApplyDefaultBulletsAndNumbers Out.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(MyDir + "Lists.ApplyDefaultBulletsAndNumbers Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "Lists.ApplyDefaultBulletsAndNumbers Out.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(MyDir + "Lists.ApplyDefaultBulletsAndNumbers Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "Lists.ApplyDefaultBulletsAndNumbers Out.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(MyDir + "Lists.ApplyDefaultBulletsAndNumbers Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "Lists.ApplyDefaultBulletsAndNumbers Out.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)
    paragraph.ListFormat.RemoveNumbers();
[Visual Basic]

Dim body As Body = doc.FirstSection.Body

For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.RemoveNumbers()
Next paragraph
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(MyDir + "Lists.ApplyDefaultBulletsAndNumbers Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "Lists.ApplyDefaultBulletsAndNumbers Out.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);
[Visual Basic]

Dim loadOptions As New LoadOptions()
loadOptions.LoadFormat = Aspose.Words.LoadFormat.Html
Dim doc As New Document(MyDir & "Document.LoadFormat.html", loadOptions)
Shows how to insert the HTML conntents 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.
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(MyDir + "Document.HtmlPageFromWebpage Out.doc");
[Visual Basic]

' The url of the page to load
Dim url As String = "http://www.aspose.com/"

' Create a WebClient object to easily extract the HTML from the page.
Dim client As New WebClient()
Dim pageSource As String = client.DownloadString(url)
client.Dispose()

' Get the HTML as bytes for loading into a stream.
Dim encoding As Encoding = client.Encoding
Dim pageBytes() As Byte = encoding.GetBytes(pageSource)

' Load the HTML into a stream.
Dim stream As New MemoryStream(pageBytes)

' The baseUri property should be set to ensure any relative img paths are retrieved correctly.
Dim options As New LoadOptions(Aspose.Words.LoadFormat.Html, "", url)

' Load the HTML document from stream and pass the LoadOptions object.
Dim doc As 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(MyDir & "Document.HtmlPageFromWebpage Out.doc")
Check each file in the folder and move it to the appropriate subfolder.
[C#]

// Loop through all found files.
foreach (string fileName in fileList)
{
    // Extract and display the file name without the path.
    string nameOnly = Path.GetFileName(fileName);
    Console.Write(nameOnly);

    // Check the file format and move the file to the appropriate folder.
    FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);

    // Display the document type.
    switch (info.LoadFormat)
    {
        case LoadFormat.Doc:
            Console.WriteLine("\tMicrosoft Word 97-2003 document.");
            break;
        case LoadFormat.Dot:
            Console.WriteLine("\tMicrosoft Word 97-2003 template.");
            break;
        case LoadFormat.Docx:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document.");
            break;
        case LoadFormat.Docm:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
            break;
        case LoadFormat.Dotx:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template.");
            break;
        case LoadFormat.Dotm:
            Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
            break;
        case LoadFormat.FlatOpc:
            Console.WriteLine("\tFlat OPC document.");
            break;
        case LoadFormat.Rtf:
            Console.WriteLine("\tRTF format.");
            break;
        case LoadFormat.WordML:
            Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
            break;
        case LoadFormat.Html:
            Console.WriteLine("\tHTML format.");
            break;
        case LoadFormat.Mhtml:
            Console.WriteLine("\tMHTML (Web archive) format.");
            break;
        case LoadFormat.Odt:
            Console.WriteLine("\tOpenDocument Text.");
            break;
        case LoadFormat.Ott:
            Console.WriteLine("\tOpenDocument Text Template.");
            break;
        case LoadFormat.DocPreWord97:
            Console.WriteLine("\tMS Word 6 or Word 95 format.");
            break;
        case LoadFormat.Unknown:
        default:
            Console.WriteLine("\tUnknown format.");
            break;
    }

    // Now copy the document into the appropriate folder.
    if (info.IsEncrypted)
    {
        Console.WriteLine("\tAn encrypted document.");
        File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), true);
    }
    else
    {
        switch (info.LoadFormat)
        {
            case LoadFormat.DocPreWord97:
                File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), true);
                break;
            case LoadFormat.Unknown:
                File.Copy(fileName, Path.Combine(unknownDir, nameOnly), true);
                break;
            default:
                File.Copy(fileName, Path.Combine(supportedDir, nameOnly), true);
                break;
        }
    }
}
[Visual Basic]

' Loop through all found files.
For Each fileName As String In fileList
    ' Extract and display the file name without the path.
    Dim nameOnly As String = Path.GetFileName(fileName)
    Console.Write(nameOnly)

    ' Check the file format and move the file to the appropriate folder.
    Dim info As FileFormatInfo = FileFormatUtil.DetectFileFormat(fileName)

    ' Display the document type.
    Select Case info.LoadFormat
        Case LoadFormat.Doc
            Console.WriteLine(Constants.vbTab & "Microsoft Word 97-2003 document.")
        Case LoadFormat.Dot
            Console.WriteLine(Constants.vbTab & "Microsoft Word 97-2003 template.")
        Case LoadFormat.Docx
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Free Document.")
        Case LoadFormat.Docm
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Enabled Document.")
        Case LoadFormat.Dotx
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Free Template.")
        Case LoadFormat.Dotm
            Console.WriteLine(Constants.vbTab & "Office Open XML WordprocessingML Macro-Enabled Template.")
        Case LoadFormat.FlatOpc
            Console.WriteLine(Constants.vbTab & "Flat OPC document.")
        Case LoadFormat.Rtf
            Console.WriteLine(Constants.vbTab & "RTF format.")
        Case LoadFormat.WordML
            Console.WriteLine(Constants.vbTab & "Microsoft Word 2003 WordprocessingML format.")
        Case LoadFormat.Html
            Console.WriteLine(Constants.vbTab & "HTML format.")
        Case LoadFormat.Mhtml
            Console.WriteLine(Constants.vbTab & "MHTML (Web archive) format.")
        Case LoadFormat.Odt
            Console.WriteLine(Constants.vbTab & "OpenDocument Text.")
        Case LoadFormat.Ott
            Console.WriteLine(Constants.vbTab & "OpenDocument Text Template.")
        Case LoadFormat.DocPreWord97
            Console.WriteLine(Constants.vbTab & "MS Word 6 or Word 95 format.")
        Case Else
            Console.WriteLine(Constants.vbTab & "Unknown format.")
    End Select

    ' Now copy the document into the appropriate folder.
    If info.IsEncrypted Then
        Console.WriteLine(Constants.vbTab & "An encrypted document.")
        File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), True)
    Else
        Select Case info.LoadFormat
            Case LoadFormat.DocPreWord97
                File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), True)
            Case LoadFormat.Unknown
                File.Copy(fileName, Path.Combine(unknownDir, nameOnly), True)
            Case Else
                File.Copy(fileName, Path.Combine(supportedDir, nameOnly), True)
        End Select
    End If
Next fileName

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
DocPreWord97 | 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
Odt | ODF Text Document. | 60
Ott | ODF Text Document Template. | 61
Text | Plain Text | 62
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

[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"));
[Visual Basic]

Dim doc As New Document(MyDir & "Document.LoadEncrypted.doc", New LoadOptions("qwerty"))
Opens an HTML document with images from a stream using a base URI.
[C#]

// 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.
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;
Document doc = new Document(stream, loadOptions);

// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();

// Save in the DOC format.
doc.Save(MyDir + "Document.OpenFromStreamWithBaseUri Out.doc");
[Visual Basic]

' 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>
Dim fileName As String = MyDir & "Document.OpenFromStreamWithBaseUri.html"

' Open the stream.
Dim stream As 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.
Dim loadOptions As New LoadOptions()
loadOptions.BaseUri = MyDir
Dim doc As New Document(stream, loadOptions)

' You can close the stream now, it is no longer needed because the document is in memory.
stream.Close()

' Save in the DOC format.
doc.Save(MyDir & "Document.OpenFromStreamWithBaseUri Out.doc")

Requirements

Namespace: Aspose.Words

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

See Also

LoadOptions Members | Aspose.Words Namespace


LoadOptions Members

LoadOptions overview

Public Instance Constructors

LoadOptions Overloaded. Initializes a new instance of the LoadOptions class.

Public Instance Properties

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.
Encoding | Gets or sets the encoding that will be used to load an HTML document if the encoding is not specified in HTML. Can be null. Default is null.
LoadFormat | Specifies the format of the document to be loaded. Default is Auto.
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.
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();

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"));
[Visual Basic]

Dim doc As 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 conntents 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.
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(MyDir + "Document.HtmlPageFromWebpage Out.doc");
[Visual Basic]

' The url of the page to load
Dim url As String = "http://www.aspose.com/"

' Create a WebClient object to easily extract the HTML from the page.
Dim client As New WebClient()
Dim pageSource As String = client.DownloadString(url)
client.Dispose()

' Get the HTML as bytes for loading into a stream.
Dim encoding As Encoding = client.Encoding
Dim pageBytes() As Byte = encoding.GetBytes(pageSource)

' Load the HTML into a stream.
Dim stream As New MemoryStream(pageBytes)

' The baseUri property should be set to ensure any relative img paths are retrieved correctly.
Dim options As New LoadOptions(Aspose.Words.LoadFormat.Html, "", url)

' Load the HTML document from stream and pass the LoadOptions object.
Dim doc As 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(MyDir & "Document.HtmlPageFromWebpage Out.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 Instance Properties

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.
Encoding | Gets or sets the encoding that will be used to load an HTML document if the encoding is not specified in HTML. Can be null. Default is null.
LoadFormat | Specifies the format of the document to be loaded. Default is Auto.
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.
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


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#]

// 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.
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;
Document doc = new Document(stream, loadOptions);

// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();

// Save in the DOC format.
doc.Save(MyDir + "Document.OpenFromStreamWithBaseUri Out.doc");
[Visual Basic]

' 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>
Dim fileName As String = MyDir & "Document.OpenFromStreamWithBaseUri.html"

' Open the stream.
Dim stream As 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.
Dim loadOptions As New LoadOptions()
loadOptions.BaseUri = MyDir
Dim doc As New Document(stream, loadOptions)

' You can close the stream now, it is no longer needed because the document is in memory.
stream.Close()

' Save in the DOC format.
doc.Save(MyDir & "Document.OpenFromStreamWithBaseUri Out.doc")

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 document if the encoding is not specified in HTML. 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 documents.

If encoding is not specified in HTML and this property is null, then the system will try to automatically detect the encoding.

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.

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.

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.

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;}

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;}

See Also

LoadOptions Class | Aspose.Words Namespace


MsWordVersion Enumeration

Allows Aspose.Wods to mimic MS Word version-specific application behavior.

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

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

Requirements

Namespace: Aspose.Words

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

See Also

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);
[Visual Basic]

Dim paragraph As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 0, True), Paragraph)
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);
[Visual Basic]

' Create a new empty document.
Dim doc As New Document()

' Add some text to the first paragraph
Dim para As Paragraph = doc.FirstSection.Body.FirstParagraph
para.AppendChild(New Run(doc, "Some text"))

' Clone the paragraph and the child nodes.
Dim cloneWithChildren As Node = para.Clone(True)
' Only clone the paragraph and no child nodes.
Dim cloneWithoutChildren As Node = 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;
}
[Visual Basic]

' Get the section that we want to work on.
Dim section As Section = doc.Sections(0)
Dim body As Body = section.Body

' Select the first child node in the body.
Dim curNode As Node = body.FirstChild

Do While curNode IsNot Nothing
    ' 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.
    Dim nextNode As Node = 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) Then
        curNode.Remove()
    End If

    ' Continue going through child nodes until null (no more siblings) is reached.
    curNode = nextNode
Loop

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 | Creates a duplicate of the node.
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.
ToTxt | Obsolete. Exports the content of the node into a string in plain text 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));
[Visual Basic]

' Open a file from disk.
Dim doc As New Document()

' Creating a new node of any type requires a document passed into the constructor.
Dim para As New Paragraph(doc)

' The new paragraph node does not yet have a parent.
Console.WriteLine("Paragraph has no parent node: " & (para.ParentNode Is Nothing))

' But the paragraph node knows its document.
Console.WriteLine("Both nodes' documents are the same: " & (para.Document Is 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 IsNot Nothing))

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);
    }
}
[Visual Basic]

Public Sub RecurseAllNodes()
    ' Open a document.
    Dim doc As New Document(MyDir & "Node.RecurseAllNodes.doc")

    ' Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc)
End Sub

''' <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 Sub TraverseAllNodes(ByVal parentNode As CompositeNode)
    ' This is the most efficient way to loop through immediate children of a node.
    Dim childNode As Node = parentNode.FirstChild
    Do While childNode IsNot Nothing
        ' Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType))

        ' Recurse into the node if it is a composite node.
        If childNode.IsComposite Then
            TraverseAllNodes(CType(childNode, CompositeNode))
        End If
        childNode = childNode.NextSibling
    Loop
End Sub

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));
}
[Visual Basic]

' Get the section that we want to work on.
Dim section As Section = doc.Sections(0)
Dim body As Body = section.Body

' Loop starting from the first child until we reach null.
Dim node As Node = body.FirstChild
Do While node IsNot Nothing
    ' Output the types of the nodes that we come across.
    Console.WriteLine(Node.NodeTypeToString(node.NodeType))
    node = node.NextSibling
Loop
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);
    }
}
[Visual Basic]

Public Sub RecurseAllNodes()
    ' Open a document.
    Dim doc As New Document(MyDir & "Node.RecurseAllNodes.doc")

    ' Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc)
End Sub

''' <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 Sub TraverseAllNodes(ByVal parentNode As CompositeNode)
    ' This is the most efficient way to loop through immediate children of a node.
    Dim childNode As Node = parentNode.FirstChild
    Do While childNode IsNot Nothing
        ' Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType))

        ' Recurse into the node if it is a composite node.
        If childNode.IsComposite Then
            TraverseAllNodes(CType(childNode, CompositeNode))
        End If
        childNode = childNode.NextSibling
    Loop
End Sub

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));
}
[Visual Basic]

' Get the section that we want to work on.
Dim section As Section = doc.Sections(0)
Dim body As Body = section.Body

' Loop starting from the first child until we reach null.
Dim node As Node = body.FirstChild
Do While node IsNot Nothing
    ' Output the types of the nodes that we come across.
    Console.WriteLine(Node.NodeTypeToString(node.NodeType))
    node = node.NextSibling
Loop
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;
}
[Visual Basic]

' Get the section that we want to work on.
Dim section As Section = doc.Sections(0)
Dim body As Body = section.Body

' Select the first child node in the body.
Dim curNode As Node = body.FirstChild

Do While curNode IsNot Nothing
    ' 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.
    Dim nextNode As Node = 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) Then
        curNode.Remove()
    End If

    ' Continue going through child nodes until null (no more siblings) is reached.
    curNode = nextNode
Loop
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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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));
[Visual Basic]

' Create a new empty document. It has one section.
Dim doc As New Document()

' The section is the first child node of the document.
Dim section As Node = doc.FirstChild

' The section's parent node is the document.
Console.WriteLine("Section parent is the document: " & (doc Is 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));
[Visual Basic]

' Open a file from disk.
Dim doc As New Document()

' Creating a new node of any type requires a document passed into the constructor.
Dim para As New Paragraph(doc)

' The new paragraph node does not yet have a parent.
Console.WriteLine("Paragraph has no parent node: " & (para.ParentNode Is Nothing))

' But the paragraph node knows its document.
Console.WriteLine("Both nodes' documents are the same: " & (para.Document Is 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 IsNot Nothing))

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);
[Visual Basic]

' 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.
Dim lastSection As Node = 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.
Dim sectionBeforeLast As Node = lastSection.PreviousSibling

If sectionBeforeLast IsNot Nothing Then
    doc.RemoveChild(sectionBeforeLast)
End If

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 a section from a Word document.

[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());
[Visual Basic]

' Open Word document.
Dim doc As 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 | Creates a duplicate of the node.
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.
ToTxt | Obsolete. Exports the content of the node into a string in plain text 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#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

See Also

Node Class | Aspose.Words Namespace


Node.Clone Method

Creates a duplicate of the node.

[Visual Basic]
Public Function Clone( _
ByVal isCloneChildren As Boolean _
) As Node
[C#]
public Node Clone(
bool isCloneChildren
);

Parameters

isCloneChildren
True to recursively clone the subtree under the specified node; false to clone only the node itself.

Return Value

The cloned node.

Remarks

This method serves as a copy constructor for nodes. The cloned node has no parent, but belongs to the same document as the original node.

This method always performs a deep copy of the node. The isCloneChildren parameter specifies whether to perform copy all child nodes as well.

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);
[Visual Basic]

' Create a new empty document.
Dim doc As New Document()

' Add some text to the first paragraph
Dim para As Paragraph = doc.FirstSection.Body.FirstParagraph
para.AppendChild(New Run(doc, "Some text"))

' Clone the paragraph and the child nodes.
Dim cloneWithChildren As Node = para.Clone(True)
' Only clone the paragraph and no child nodes.
Dim cloneWithoutChildren As Node = 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 Node GetAncestor(NodeType);

Gets the first ancestor of the specified object type.

public Node 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 Node
[C#]
public Node 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#]

public void CalcuateDepthOfNestedTables()
{
    Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true))
    {
        // 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)
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells)
        {
            // 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;
}
[Visual Basic]

Public Sub CalcuateDepthOfNestedTables()
    Dim doc As New Document(MyDir & "Table.NestedTables.doc")
    Dim tableIndex As Integer = 0

    For Each table As Table In doc.GetChildNodes(NodeType.Table, True)
        ' First lets find if any cells in the table have tables themselves as children.
        Dim count As Integer = 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.
        Dim tableDepth As Integer = GetNestedDepthOfTable(table)

        If tableDepth > 0 Then
            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)
        End If

        tableIndex += 1
    Next table
End Sub

''' <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 Shared Function GetNestedDepthOfTable(ByVal table As Table) As Integer
    Dim depth As Integer = 0

    Dim type As NodeType = table.NodeType
    ' The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Dim parent As Node = table.GetAncestor(type)

    Do While parent IsNot Nothing
        ' 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 += 1
        parent = parent.GetAncestor(type)
    Loop

    Return depth
End Function

''' <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 Shared Function GetChildTableCount(ByVal table As Table) As Integer
    Dim tableCount As Integer = 0
    ' Iterate through all child rows in the table
    For Each row As Row In table.Rows
        ' Iterate through all child cells in the row
        For Each Cell As Cell In row.Cells
            ' Retrieve the collection of child tables of this cell
            Dim childTables As TableCollection = Cell.Tables

            ' If this cell has a table as a child then return true
            If childTables.Count > 0 Then
                tableCount += 1
            End If
        Next Cell
    Next row

    ' No cell contains a table
    Return tableCount
End Function

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 Node
[C#]
public Node 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.doc")

See Also

Node Class | Aspose.Words Namespace | ToTxt


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;
}
[Visual Basic]

Dim curNode As Node = doc
Do While curNode IsNot Nothing
    Dim nextNode As Node = curNode.NextPreOrder(doc)

    If curNode.NodeType.Equals(NodeType.Shape) Then
        Dim shape As Shape = CType(curNode, Shape)

        ' Several shape types can have an image including image shapes and OLE objects.
        If shape.HasImage Then
            shape.Remove()
        End If
    End If

    curNode = nextNode
Loop

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));
}
[Visual Basic]

' Get the section that we want to work on.
Dim section As Section = doc.Sections(0)
Dim body As Body = section.Body

' Loop starting from the first child until we reach null.
Dim node As Node = body.FirstChild
Do While node IsNot Nothing
    ' Output the types of the nodes that we come across.
    Console.WriteLine(Node.NodeTypeToString(node.NodeType))
    node = node.NextSibling
Loop
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);
    }
}
[Visual Basic]

Public Sub RecurseAllNodes()
    ' Open a document.
    Dim doc As New Document(MyDir & "Node.RecurseAllNodes.doc")

    ' Invoke the recursive function that will walk the tree.
    TraverseAllNodes(doc)
End Sub

''' <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 Sub TraverseAllNodes(ByVal parentNode As CompositeNode)
    ' This is the most efficient way to loop through immediate children of a node.
    Dim childNode As Node = parentNode.FirstChild
    Do While childNode IsNot Nothing
        ' Do some useful work.
        Console.WriteLine(Node.NodeTypeToString(childNode.NodeType))

        ' Recurse into the node if it is a composite node.
        If childNode.IsComposite Then
            TraverseAllNodes(CType(childNode, CompositeNode))
        End If
        childNode = childNode.NextSibling
    Loop
End Sub

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)
{
    // 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();
[Visual Basic]

' 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.
Dim shapes As NodeCollection = 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.
Dim shapesToDelete As New ArrayList()
For Each shape As Shape In shapes
    ' Several shape types can have an image including image shapes and OLE objects.
    If shape.HasImage Then
        shapesToDelete.Add(shape)
    End If
Next shape

' Now we can delete shapes.
For Each shape As Shape In shapesToDelete
    shape.Remove()
Next shape
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;
}
[Visual Basic]

' Get the section that we want to work on.
Dim section As Section = doc.Sections(0)
Dim body As Body = section.Body

' Select the first child node in the body.
Dim curNode As Node = body.FirstChild

Do While curNode IsNot Nothing
    ' 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.
    Dim nextNode As Node = 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) Then
        curNode.Remove()
    End If

    ' Continue going through child nodes until null (no more siblings) is reached.
    curNode = nextNode
Loop

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);
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

' Extract the last paragraph in the document to convert to HTML.
Dim node As 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
Dim nodeAsHtml As String = 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));
[Visual Basic]

Dim doc As New Document()

' Enter a dummy field into the document.
Dim builder As 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))
{
    // 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++;
    }

}
[Visual Basic]

Dim doc As New Document(MyDir & "Lists.PrintOutAllLists.doc")
doc.UpdateListLabels()
Dim listParaCount As Integer = 1

For Each paragraph As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 Then
        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.
        Dim paragraphText As String = paragraph.ToString(SaveFormat.Text).Trim()
        Console.WriteLine("Exported Text: " & paragraphText)

        Dim label As ListLabel = 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 += 1
    End If

Next paragraph

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();
saveOptions.ExportHeadersFootersMode = ExportHeadersFootersMode.PerSection;
saveOptions.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);
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

' Extract the last paragraph in the document to convert to HTML.
Dim node As Node = doc.LastSection.Body.LastParagraph

' Create an instance of HtmlSaveOptions and set a few options.
Dim saveOptions As New HtmlSaveOptions()
saveOptions.ExportHeadersFootersMode = ExportHeadersFootersMode.PerSection
saveOptions.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.
Dim nodeAsHtml As String = node.ToString(saveOptions)

See Also

Node Class | Aspose.Words Namespace | Node.ToString Overload List


Node.ToTxt Method

NOTE: This method is now obsolete.

Use ToString(SaveFormat.Text) instead.

Exports the content of the node into a string in plain text format.

[Visual Basic]
Public Function ToTxt() As String
[C#]
public string ToTxt();

Return Value

The content of the node in plain text format.

Remarks

This method removes field codes and Microsoft Word control characters, uses CrLf (or any other) combination of characters to mark ends of paragraphs in the resulting string. It produces a different result from GetText which just gets the text from the node without removing field codes or special characters.

See Also

Node Class | Aspose.Words Namespace | ParagraphBreak | ExportHeadersFooters


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 HandleNodeChanging_FontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(MyDir + "Document.FontChanger Out.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 HandleNodeChanging_FontChanger : 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
    }
}
[Visual Basic]

Public Sub TestNodeChangingInDocument()
    ' Create a blank document object
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    ' Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = New HandleNodeChanging_FontChanger()

    ' Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>")

    doc.Save(MyDir & "Document.FontChanger Out.doc")

    ' Check that the inserted content has the correct formatting
    Dim run As Run = CType(doc.GetChild(NodeType.Run, 0, True), Run)
    Assert.AreEqual(24.0, run.Font.Size)
    Assert.AreEqual("Arial", run.Font.Name)
End Sub

Public Class HandleNodeChanging_FontChanger
    Implements INodeChangingCallback
    ' Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    Private Sub NodeInserted(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserted
        ' Change the font of inserted text contained in the Run nodes.
        If args.Node.NodeType = NodeType.Run Then
            Dim font As Aspose.Words.Font = (CType(args.Node, Run)).Font
            font.Size = 24
            font.Name = "Arial"
        End If
    End Sub

    Private Sub NodeInserting(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserting
        ' Do Nothing
    End Sub

    Private Sub NodeRemoved(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoved
        ' Do Nothing
    End Sub

    Private Sub NodeRemoving(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoving
        ' Do Nothing
    End Sub
End Class

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 HandleNodeChanging_FontChanger();

    // Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>");

    doc.Save(MyDir + "Document.FontChanger Out.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 HandleNodeChanging_FontChanger : 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
    }
}
[Visual Basic]

Public Sub TestNodeChangingInDocument()
    ' Create a blank document object
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    ' Set up and pass the object which implements the handler methods.
    doc.NodeChangingCallback = New HandleNodeChanging_FontChanger()

    ' Insert sample HTML content
    builder.InsertHtml("<p>Hello World</p>")

    doc.Save(MyDir & "Document.FontChanger Out.doc")

    ' Check that the inserted content has the correct formatting
    Dim run As Run = CType(doc.GetChild(NodeType.Run, 0, True), Run)
    Assert.AreEqual(24.0, run.Font.Size)
    Assert.AreEqual("Arial", run.Font.Name)
End Sub

Public Class HandleNodeChanging_FontChanger
    Implements INodeChangingCallback
    ' Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
    Private Sub NodeInserted(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserted
        ' Change the font of inserted text contained in the Run nodes.
        If args.Node.NodeType = NodeType.Run Then
            Dim font As Aspose.Words.Font = (CType(args.Node, Run)).Font
            font.Size = 24
            font.Name = "Arial"
        End If
    End Sub

    Private Sub NodeInserting(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeInserting
        ' Do Nothing
    End Sub

    Private Sub NodeRemoved(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoved
        ' Do Nothing
    End Sub

    Private Sub NodeRemoving(ByVal args As NodeChangingArgs) Implements INodeChangingCallback.NodeRemoving
        ' Do Nothing
    End Sub
End Class

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
[C#]
public class NodeCollection : 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)
{
    // 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(MyDir + "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(MyDir + "Shape.ReplaceTextboxesWithImages Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Shape.ReplaceTextboxesWithImages.doc")

' This gets a live collection of all shape nodes in the document.
Dim shapeCollection As NodeCollection = 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.
Dim shapes() As Node = shapeCollection.ToArray()

For Each shape As Shape In shapes
    ' Filter out all shapes that we don't need.
    If shape.ShapeType.Equals(ShapeType.TextBox) Then
        ' Create a new shape that will replace the existing shape.
        Dim image As New Shape(doc, ShapeType.Image)

        ' Load the image into the new shape.
        image.ImageData.SetImage(MyDir & "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()
    End If
Next shape

doc.Save(MyDir & "Shape.ReplaceTextboxesWithImages Out.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 | Provides a simple "foreach" style iteration over the collection of nodes.
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);
    }
}
[Visual Basic]

Dim children As NodeCollection = paragraph.ChildNodes
For i As Integer = 0 To children.Count - 1
    Dim child As Node = children(i)

    ' Paragraph may contain children of various types such as runs, shapes and so on.
    If child.NodeType.Equals(NodeType.Run) Then
        ' Say we found the node that we want, do something useful.
        Dim run As Run = CType(child, Run)
        Console.WriteLine(run.Text)
    End If
Next i
Shows how to find out if a table contains another table or if the table itself is nested inside another table.
[C#]

public void CalcuateDepthOfNestedTables()
{
    Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true))
    {
        // 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)
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells)
        {
            // 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;
}
[Visual Basic]

Public Sub CalcuateDepthOfNestedTables()
    Dim doc As New Document(MyDir & "Table.NestedTables.doc")
    Dim tableIndex As Integer = 0

    For Each table As Table In doc.GetChildNodes(NodeType.Table, True)
        ' First lets find if any cells in the table have tables themselves as children.
        Dim count As Integer = 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.
        Dim tableDepth As Integer = GetNestedDepthOfTable(table)

        If tableDepth > 0 Then
            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)
        End If

        tableIndex += 1
    Next table
End Sub

''' <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 Shared Function GetNestedDepthOfTable(ByVal table As Table) As Integer
    Dim depth As Integer = 0

    Dim type As NodeType = table.NodeType
    ' The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Dim parent As Node = table.GetAncestor(type)

    Do While parent IsNot Nothing
        ' 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 += 1
        parent = parent.GetAncestor(type)
    Loop

    Return depth
End Function

''' <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 Shared Function GetChildTableCount(ByVal table As Table) As Integer
    Dim tableCount As Integer = 0
    ' Iterate through all child rows in the table
    For Each row As Row In table.Rows
        ' Iterate through all child cells in the row
        For Each Cell As Cell In row.Cells
            ' Retrieve the collection of child tables of this cell
            Dim childTables As TableCollection = Cell.Tables

            ' If this cell has a table as a child then return true
            If childTables.Count > 0 Then
                tableCount += 1
            End If
        Next Cell
    Next row

    ' No cell contains a table
    Return tableCount
End Function

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);
    }
}
[Visual Basic]

Dim children As NodeCollection = paragraph.ChildNodes
For i As Integer = 0 To children.Count - 1
    Dim child As Node = children(i)

    ' Paragraph may contain children of various types such as runs, shapes and so on.
    If child.NodeType.Equals(NodeType.Run) Then
        ' Say we found the node that we want, do something useful.
        Dim run As Run = CType(child, Run)
        Console.WriteLine(run.Text)
    End If
Next i

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 | Provides a simple "foreach" style iteration over the collection of nodes.
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);
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim sectionToAdd As 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();
[Visual Basic]

Dim doc As 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

Provides a simple "foreach" style iteration over the collection of nodes.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Return Value

An IEnumerator.

Implements

IEnumerable.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);
[Visual Basic]

Dim allTables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)
Dim tableIndex As Integer = 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)
{
    // 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)
    {
        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)
        {
            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();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As 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).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table

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());
[Visual Basic]

' Open the document.
Dim doc As 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.
Dim lastSectionIdx As Integer = doc.Sections.Count - 1
Dim newSection As Section = 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)
{
    // 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(MyDir + "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(MyDir + "Shape.ReplaceTextboxesWithImages Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Shape.ReplaceTextboxesWithImages.doc")

' This gets a live collection of all shape nodes in the document.
Dim shapeCollection As NodeCollection = 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.
Dim shapes() As Node = shapeCollection.ToArray()

For Each shape As Shape In shapes
    ' Filter out all shapes that we don't need.
    If shape.ShapeType.Equals(ShapeType.TextBox) Then
        ' Create a new shape that will replace the existing shape.
        Dim image As New Shape(doc, ShapeType.Image)

        ' Load the image into the new shape.
        image.ImageData.SetImage(MyDir & "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()
    End If
Next shape

doc.Save(MyDir & "Shape.ReplaceTextboxesWithImages Out.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.

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 Constructor 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.

[Visual Basic]
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.

See Also

NodeImporter Class | Aspose.Words Namespace


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.

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
[C#]
public class NodeList : 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.Text;
using System.Text.RegularExpressions;
using Aspose.Words;
using Aspose.Words.Fields;

namespace Examples
{
    /// <summary>
    /// Shows how to replace hyperlinks in a Word document.
    /// </summary>
    public class ExReplaceHyperlinks : ExBase
    {
        /// <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)
            {
                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(MyDir + "ReplaceHyperlinks Out.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
            {
                string dummy = null;  // This is needed to fool the C# to VB.NET converter.
                return mTarget;
            }
            set
            {
                mTarget = value;
                UpdateFieldCode();
            }
        }

        /// <summary>
        /// True if the hyperlink's 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
            );
    }
}
[Visual Basic]

Imports Microsoft.VisualBasic
Imports System
Imports System.Text
Imports System.Text.RegularExpressions
Imports Aspose.Words
Imports Aspose.Words.Fields

Namespace Examples
    ''' <summary>
    ''' Shows how to replace hyperlinks in a Word document.
    ''' </summary>
    <TestFixture> _
    Public Class ExReplaceHyperlinks
        Inherits ExBase
        ''' <summary>
        ''' Finds all hyperlinks in a Word document and changes their URL and display name.
        ''' </summary>
        <Test> _
        Public Sub ReplaceHyperlinks()
            ' Specify your document name here.
            Dim doc As New Document(MyDir & "ReplaceHyperlinks.doc")

            ' Hyperlinks in a Word documents are fields, select all field start nodes so we can find the hyperlinks.
            Dim fieldStarts As NodeList = doc.SelectNodes("//FieldStart")
            For Each fieldStart As FieldStart In fieldStarts
                If fieldStart.FieldType.Equals(FieldType.FieldHyperlink) Then
                    ' The field is a hyperlink field, use the "facade" class to help to deal with the field.
                    Dim hyperlink As New Hyperlink(fieldStart)

                    ' Some hyperlinks can be local (links to bookmarks inside the document), ignore these.
                    If hyperlink.IsLocal Then
                        Continue For
                    End If

                    ' 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
                End If
            Next fieldStart

            doc.Save(MyDir & "ReplaceHyperlinks Out.doc")
        End Sub

        Private Const NewUrl As String = "http://www.aspose.com"
        Private Const NewName As String = "Aspose - The .NET & Java Component Publisher"
    End Class

    ''' <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>
    Friend Class Hyperlink
        Friend Sub New(ByVal fieldStart As FieldStart)
            If fieldStart Is Nothing Then
                Throw New ArgumentNullException("fieldStart")
            End If
            If (Not fieldStart.FieldType.Equals(FieldType.FieldHyperlink)) Then
                Throw New ArgumentException("Field start type must be FieldHyperlink.")
            End If

            mFieldStart = fieldStart

            ' Find the field separator node.
            mFieldSeparator = FindNextSibling(mFieldStart, NodeType.FieldSeparator)
            If mFieldSeparator Is Nothing Then
                Throw New InvalidOperationException("Cannot find field separator.")
            End If

            ' 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.
            Dim fieldCode As String = GetTextSameParent(mFieldStart.NextSibling, mFieldSeparator)
            Dim match As 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
        End Sub

        ''' <summary>
        ''' Gets or sets the display name of the hyperlink.
        ''' </summary>
        Friend Property Name() As String
            Get
                Return GetTextSameParent(mFieldSeparator, mFieldEnd)
            End Get
            Set(ByVal value As String)
                ' Hyperlink display name is stored in the field result which is a Run
                ' node between field separator and field end.
                Dim fieldResult As Run = CType(mFieldSeparator.NextSibling, Run)
                fieldResult.Text = value

                ' But sometimes the field result can consist of more than one run, delete these runs.
                RemoveSameParent(fieldResult.NextSibling, mFieldEnd)
            End Set
        End Property

        ''' <summary>
        ''' Gets or sets the target url or bookmark name of the hyperlink.
        ''' </summary>
        Friend Property Target() As String
            Get
                Dim dummy As String = Nothing ' This is needed to fool the C# to VB.NET converter.
                Return mTarget
            End Get
            Set(ByVal value As String)
                mTarget = value
                UpdateFieldCode()
            End Set
        End Property

        ''' <summary>
        ''' True if the hyperlink's target is a bookmark inside the document. False if the hyperlink is a url.
        ''' </summary>
        Friend Property IsLocal() As Boolean
            Get
                Return mIsLocal
            End Get
            Set(ByVal value As Boolean)
                mIsLocal = value
                UpdateFieldCode()
            End Set
        End Property

        Private Sub UpdateFieldCode()
            ' Field code is stored in a Run node between field start and field separator.
            Dim fieldCode As Run = CType(mFieldStart.NextSibling, Run)
            fieldCode.Text = String.Format("HYPERLINK {0}""{1}""", (If((mIsLocal), "\l ", "")), mTarget)

            ' But sometimes the field code can consist of more than one run, delete these runs.
            RemoveSameParent(fieldCode.NextSibling, mFieldSeparator)
        End Sub

        ''' <summary>
        ''' Goes through siblings starting from the start node until it finds a node of the specified type or null.
        ''' </summary>
        Private Shared Function FindNextSibling(ByVal startNode As Node, ByVal nodeType As NodeType) As Node
            Dim node As Node = startNode
            Do While node IsNot Nothing
                If node.NodeType.Equals(nodeType) Then
                    Return node
                End If
                node = node.NextSibling
            Loop
            Return Nothing
        End Function

        ''' <summary>
        ''' Retrieves text from start up to but not including the end node.
        ''' </summary>
        Private Shared Function GetTextSameParent(ByVal startNode As Node, ByVal endNode As Node) As String
            If (endNode IsNot Nothing) AndAlso (startNode.ParentNode IsNot endNode.ParentNode) Then
                Throw New ArgumentException("Start and end nodes are expected to have the same parent.")
            End If

            Dim builder As New StringBuilder()
            Dim child As Node = startNode
            Do While Not child.Equals(endNode)
                builder.Append(child.GetText())
                child = child.NextSibling
            Loop

            Return builder.ToString()
        End Function

        ''' <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 Shared Sub RemoveSameParent(ByVal startNode As Node, ByVal endNode As Node)
            If (endNode IsNot Nothing) AndAlso (startNode.ParentNode IsNot endNode.ParentNode) Then
                Throw New ArgumentException("Start and end nodes are expected to have the same parent.")
            End If

            Dim curChild As Node = startNode
            Do While (curChild IsNot Nothing) AndAlso (curChild IsNot endNode)
                Dim nextChild As Node = curChild.NextSibling
                curChild.Remove()
                curChild = nextChild
            Loop
        End Sub

        Private ReadOnly mFieldStart As Node
        Private ReadOnly mFieldSeparator As Node
        Private ReadOnly mFieldEnd As Node
        Private mIsLocal As Boolean
        Private mTarget As String

        ''' <summary>
        ''' RK I am notoriously bad at regexes. It seems I don't understand their way of thinking.
        ''' </summary>
        Private Shared ReadOnly gRegex As New Regex("\S+" & "\s+" & "(?:""""\s+)?" & "(\\l\s+)?" & """" &                  "([^""]+)" &          """"                )
    End Class
End Namespace

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Return Value

An IEnumerator.

Implements

IEnumerable.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;
[Visual Basic]

Dim doc As New Document()

' Returns NodeType.Document
Dim type As NodeType = 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
CustomXmlMarkup | Allows to define customer-specific semantics by applying XML elements defined by any schema syntax (XML Schema, NVDL, etc.) around inline structures (runs, images, fields, etc.), paragraphs, tables, rows and cells. | 28
StructuredDocumentTag | Allows to define customer-specific information and its means of presentation. | 29
GlossaryDocument | A glossary document within the main document. | 30
BuildingBlock | A building block within a glossary document (e.g. glossary document entry). | 31
CommentRangeStart | A marker node that represents the start of a commented range. | 32
CommentRangeEnd | A marker node that represents the end of a commented range. | 33
DrawingML | A DrawingML object. It can be a picture, locked canvas, diagram or a chart from the OOXML specification. | 34
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. | 35
SubDocument | A subdocument node which is a link to another document. | 36
System | Reserved for internal use by Aspose.Words. | 37
Null | Reserved for internal use by Aspose.Words. | 38

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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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
NumInDash |  | 57
LowercaseRussian | Lowercase Russian alphabet | 58
UppercaseRussian | Uppercase Russian alphabet | 59
None | No bullet or number. | 255

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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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 = System.Drawing.Color.Blue;
border.DistanceFromText = 0;

doc.Save(MyDir + "PageSetup.PageBorderTop Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim ps As PageSetup = doc.Sections(0).PageSetup
ps.BorderAlwaysInFront = False
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage

Dim border As Border = ps.Borders(BorderType.Top)
border.LineStyle = LineStyle.Single
border.LineWidth = 30
border.Color = System.Drawing.Color.Blue
border.DistanceFromText = 0

doc.Save(MyDir & "PageSetup.PageBorderTop Out.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 = System.Drawing.Color.Blue;
border.DistanceFromText = 0;

doc.Save(MyDir + "PageSetup.PageBorderTop Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim ps As PageSetup = doc.Sections(0).PageSetup
ps.BorderAlwaysInFront = False
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage

Dim border As Border = ps.Borders(BorderType.Top)
border.LineStyle = LineStyle.Single
border.LineWidth = 30
border.Color = System.Drawing.Color.Blue
border.DistanceFromText = 0

doc.Save(MyDir & "PageSetup.PageBorderTop Out.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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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.
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.
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.
LineStartingNumber | Gets or sets the starting line number.
MirrorMargins | Obsolete. For multiple page documents, swaps left and right margins on facing pages.
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.
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.
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.
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.
LineStartingNumber | Gets or sets the starting line number.
MirrorMargins | Obsolete. For multiple page documents, swaps left and right margins on facing pages.
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.
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.

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 = System.Drawing.Color.Blue;
border.DistanceFromText = 0;

doc.Save(MyDir + "PageSetup.PageBorderTop Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim ps As PageSetup = doc.Sections(0).PageSetup
ps.BorderAlwaysInFront = False
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage

Dim border As Border = ps.Borders(BorderType.Top)
border.LineStyle = LineStyle.Single
border.LineWidth = 30
border.Color = System.Drawing.Color.Blue
border.DistanceFromText = 0

doc.Save(MyDir & "PageSetup.PageBorderTop Out.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 = System.Drawing.Color.Blue;
border.DistanceFromText = 0;

doc.Save(MyDir + "PageSetup.PageBorderTop Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim ps As PageSetup = doc.Sections(0).PageSetup
ps.BorderAlwaysInFront = False
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage

Dim border As Border = ps.Borders(BorderType.Top)
border.LineStyle = LineStyle.Single
border.LineWidth = 30
border.Color = System.Drawing.Color.Blue
border.DistanceFromText = 0

doc.Save(MyDir & "PageSetup.PageBorderTop Out.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 = System.Drawing.Color.Blue;
border.DistanceFromText = 0;

doc.Save(MyDir + "PageSetup.PageBorderTop Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim ps As PageSetup = doc.Sections(0).PageSetup
ps.BorderAlwaysInFront = False
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage

Dim border As Border = ps.Borders(BorderType.Top)
border.LineStyle = LineStyle.Single
border.LineWidth = 30
border.Color = System.Drawing.Color.Blue
border.DistanceFromText = 0

doc.Save(MyDir & "PageSetup.PageBorderTop Out.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 = System.Drawing.Color.Green;
ps.Borders.DistanceFromText = 24;
ps.Borders.Shadow = true;

doc.Save(MyDir + "PageSetup.PageBorders Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim ps As PageSetup = doc.Sections(0).PageSetup

ps.Borders.LineStyle = LineStyle.DoubleWave
ps.Borders.LineWidth = 2
ps.Borders.Color = System.Drawing.Color.Green
ps.Borders.DistanceFromText = 24
ps.Borders.Shadow = True

doc.Save(MyDir & "PageSetup.PageBorders Out.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.

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.

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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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;

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(MyDir + "PageSetup.DifferentHeaders Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.DifferentFirstPageHeaderFooter = True
ps.OddAndEvenPagesHeaderFooter = True

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(MyDir & "PageSetup.DifferentHeaders Out.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(MyDir + "DocumentBuilder.HeadersAndFooters Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.HeadersAndFooters Out.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 FootnoteOptions
[C#]
public FootnoteOptions EndnoteOptions {get;}

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.
System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.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)
{
    section.PageSetup.FirstPageTray = settings.DefaultPageSettings.PaperSource.RawKind;
    section.PageSetup.OtherPagesTray = settings.DefaultPageSettings.PaperSource.RawKind;
}
[Visual Basic]

Dim doc As 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.
Dim settings As New System.Drawing.Printing.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.
For Each section As Section In doc.Sections
    section.PageSetup.FirstPageTray = settings.DefaultPageSettings.PaperSource.RawKind
    section.PageSetup.OtherPagesTray = settings.DefaultPageSettings.PaperSource.RawKind
Next section
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.
System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.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)
{
    if(section.PageSetup.PaperSize == PaperSize.Letter)
    {
        section.PageSetup.FirstPageTray = printerTrayForLetter;
        section.PageSetup.OtherPagesTray = printerTrayForLetter;
    }
    else if(section.PageSetup.PaperSize == PaperSize.A4)
    {
        section.PageSetup.FirstPageTray = printerTrayForA4;
        section.PageSetup.OtherPagesTray = printerTrayForA4;
    }
}
[Visual Basic]

Dim doc As New Document()

' Choose the default printer to be used for printing this document.
Dim settings As New System.Drawing.Printing.PrinterSettings()

' This is the tray we will use for A4 paper size. This is the first tray in the paper sources collection.
Dim printerTrayForA4 As Integer = 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.
Dim printerTrayForLetter As Integer = settings.PaperSources(1).RawKind

' Set the page tray used for each section based off the paper size used in the section.
For Each section As Section In doc.Sections
    If section.PageSetup.PaperSize = PaperSize.Letter Then
        section.PageSetup.FirstPageTray = printerTrayForLetter
        section.PageSetup.OtherPagesTray = printerTrayForLetter
    ElseIf section.PageSetup.PaperSize = PaperSize.A4 Then
        section.PageSetup.FirstPageTray = printerTrayForA4
        section.PageSetup.OtherPagesTray = printerTrayForA4
    End If
Next section

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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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;}

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;}

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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(MyDir + "PageSetup.LineNumbers Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.LineStartingNumber = 1
ps.LineNumberCountBy = 5
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage

For i As Integer = 1 To 20
    builder.Writeln(String.Format("Line {0}.", i))
Next i

builder.Document.Save(MyDir & "PageSetup.LineNumbers Out.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.

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;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(MyDir + "PageSetup.LineNumbers Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.LineStartingNumber = 1
ps.LineNumberCountBy = 5
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage

For i As Integer = 1 To 20
    builder.Writeln(String.Format("Line {0}.", i))
Next i

builder.Document.Save(MyDir & "PageSetup.LineNumbers Out.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;

for (int i = 1; i <= 20; i++)
    builder.Writeln(string.Format("Line {0}.", i));

builder.Document.Save(MyDir + "PageSetup.LineNumbers Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.LineStartingNumber = 1
ps.LineNumberCountBy = 5
ps.LineNumberRestartMode = LineNumberRestartMode.RestartPage

For i As Integer = 1 To 20
    builder.Writeln(String.Format("Line {0}.", i))
Next i

builder.Document.Save(MyDir & "PageSetup.LineNumbers Out.doc")

See Also

PageSetup Class | Aspose.Words Namespace


MirrorMargins Property

Aspose.Words

PageSetup.MirrorMargins Property

NOTE: This property is now obsolete.

Please use the MultiplePages property to set MultiplePagesType.

For multiple page documents, swaps left and right margins on facing pages.

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

Remarks

Note, changing this property affects all sections in the document.

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;}

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;

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(MyDir + "PageSetup.DifferentHeaders Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.DifferentFirstPageHeaderFooter = True
ps.OddAndEvenPagesHeaderFooter = True

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(MyDir & "PageSetup.DifferentHeaders Out.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(MyDir + "DocumentBuilder.HeadersAndFooters Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.HeadersAndFooters Out.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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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.
System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.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)
{
    section.PageSetup.FirstPageTray = settings.DefaultPageSettings.PaperSource.RawKind;
    section.PageSetup.OtherPagesTray = settings.DefaultPageSettings.PaperSource.RawKind;
}
[Visual Basic]

Dim doc As 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.
Dim settings As New System.Drawing.Printing.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.
For Each section As Section In doc.Sections
    section.PageSetup.FirstPageTray = settings.DefaultPageSettings.PaperSource.RawKind
    section.PageSetup.OtherPagesTray = settings.DefaultPageSettings.PaperSource.RawKind
Next section
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.
System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.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)
{
    if(section.PageSetup.PaperSize == PaperSize.Letter)
    {
        section.PageSetup.FirstPageTray = printerTrayForLetter;
        section.PageSetup.OtherPagesTray = printerTrayForLetter;
    }
    else if(section.PageSetup.PaperSize == PaperSize.A4)
    {
        section.PageSetup.FirstPageTray = printerTrayForA4;
        section.PageSetup.OtherPagesTray = printerTrayForA4;
    }
}
[Visual Basic]

Dim doc As New Document()

' Choose the default printer to be used for printing this document.
Dim settings As New System.Drawing.Printing.PrinterSettings()

' This is the tray we will use for A4 paper size. This is the first tray in the paper sources collection.
Dim printerTrayForA4 As Integer = 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.
Dim printerTrayForLetter As Integer = settings.PaperSources(1).RawKind

' Set the page tray used for each section based off the paper size used in the section.
For Each section As Section In doc.Sections
    If section.PageSetup.PaperSize = PaperSize.Letter Then
        section.PageSetup.FirstPageTray = printerTrayForLetter
        section.PageSetup.OtherPagesTray = printerTrayForLetter
    ElseIf section.PageSetup.PaperSize = PaperSize.A4 Then
        section.PageSetup.FirstPageTray = printerTrayForA4
        section.PageSetup.OtherPagesTray = printerTrayForA4
    End If
Next section

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(MyDir + "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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(MyDir + "DocumentBuilder.InsertWatermark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)

Dim image As Image = Image.FromFile(MyDir & "Watermark.png")

' Insert a floating picture.
Dim shape As 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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2

doc.Save(MyDir & "DocumentBuilder.InsertWatermark Out.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 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(MyDir + "PageSetup.PageNumbering Out.doc");
[Visual Basic]

' This document has two sections, but no page numbers yet.
Dim doc As 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".
Dim builder As New DocumentBuilder(doc)
builder.MoveToSection(0)
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary)
builder.Write("Page ")
builder.InsertField("PAGE", "")

' Set first section page numbering.
Dim section As Section = doc.Sections(0)
section.PageSetup.RestartPageNumbering = True
section.PageSetup.PageStartingNumber = 5
section.PageSetup.PageNumberStyle = NumberStyle.UppercaseRoman

' Create a header for the section 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(MyDir & "PageSetup.PageNumbering Out.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 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(MyDir + "PageSetup.PageNumbering Out.doc");
[Visual Basic]

' This document has two sections, but no page numbers yet.
Dim doc As 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".
Dim builder As New DocumentBuilder(doc)
builder.MoveToSection(0)
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary)
builder.Write("Page ")
builder.InsertField("PAGE", "")

' Set first section page numbering.
Dim section As Section = doc.Sections(0)
section.PageSetup.RestartPageNumbering = True
section.PageSetup.PageStartingNumber = 5
section.PageSetup.PageNumberStyle = NumberStyle.UppercaseRoman

' Create a header for the section 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(MyDir & "PageSetup.PageNumbering Out.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

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 + "Hammer.wmf");

// 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;

// Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0;
shape.Top = 0;
shape.Width = builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;

builder.Document.Save(MyDir + "Image.CreateFloatingPositionSize Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "Hammer.wmf")

' 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

' Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0
shape.Top = 0
shape.Width = builder.CurrentSection.PageSetup.PageWidth
shape.Height = 50

builder.Document.Save(MyDir & "Image.CreateFloatingPositionSize Out.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(MyDir + "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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(MyDir + "DocumentBuilder.InsertWatermark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)

Dim image As Image = Image.FromFile(MyDir & "Watermark.png")

' Insert a floating picture.
Dim shape As 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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2

doc.Save(MyDir & "DocumentBuilder.InsertWatermark Out.doc")

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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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 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(MyDir + "PageSetup.PageNumbering Out.doc");
[Visual Basic]

' This document has two sections, but no page numbers yet.
Dim doc As 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".
Dim builder As New DocumentBuilder(doc)
builder.MoveToSection(0)
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary)
builder.Write("Page ")
builder.InsertField("PAGE", "")

' Set first section page numbering.
Dim section As Section = doc.Sections(0)
section.PageSetup.RestartPageNumbering = True
section.PageSetup.PageStartingNumber = 5
section.PageSetup.PageNumberStyle = NumberStyle.UppercaseRoman

' Create a header for the section 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(MyDir & "PageSetup.PageNumbering Out.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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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;}

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;
[Visual Basic]

Dim doc As 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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;}

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;}

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(MyDir + "PageSetup.ColumnsSameWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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(MyDir & "PageSetup.ColumnsSameWidth Out.doc")

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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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(MyDir + "PageSetup.ClearFormatting Out.doc");
[Visual Basic]

Dim builder As 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(MyDir & "PageSetup.ClearFormatting Out.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 = 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(MyDir + "PageSetup.PageMargins Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim ps As PageSetup = builder.PageSetup
ps.PaperSize = 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(MyDir & "PageSetup.PageMargins Out.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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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

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.
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.
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.
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.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a 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 CompositeNode) | 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.
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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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

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.
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.
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.
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


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))
    foreach (Paragraph para in cell.Paragraphs)
        if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
            para.ParagraphFormat.KeepWithNext = true;
[Visual Basic]

' 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.
For Each cell As Cell In table.GetChildNodes(NodeType.Cell, True)
    For Each para As Paragraph In cell.Paragraphs
        If Not(cell.ParentRow.IsLastRow AndAlso para.IsEndOfCell) Then
            para.ParagraphFormat.KeepWithNext = True
        End If
    Next para
Next cell

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)
    {
        // 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;
        }
    }
}
[Visual Basic]

''' <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>
Private Shared Sub InsertDocument(ByVal insertAfterNode As Node, ByVal srcDoc As Document)
    ' Make sure that the node is either a paragraph or table.
    If ((Not insertAfterNode.NodeType.Equals(NodeType.Paragraph))) And ((Not insertAfterNode.NodeType.Equals(NodeType.Table))) Then
        Throw New ArgumentException("The destination node should be either a paragraph or table.")
    End If

    ' We will be inserting into the parent of the destination paragraph.
    Dim dstStory As CompositeNode = insertAfterNode.ParentNode

    ' This object will be translating styles and lists during the import.
    Dim importer As New NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting)

    ' Loop through all sections in the source document.
    For Each srcSection As Section In srcDoc.Sections
        ' Loop through all block level nodes (paragraphs and tables) in the body of the section.
        For Each srcNode As Node In srcSection.Body
            ' Let's skip the node if it is a last empty paragraph in a section.
            If srcNode.NodeType.Equals(NodeType.Paragraph) Then
                Dim para As Paragraph = CType(srcNode, Paragraph)
                If para.IsEndOfSection AndAlso (Not para.HasChildNodes) Then
                    Continue For
                End If
            End If

            ' This creates a clone of the node, suitable for insertion into the destination document.
            Dim newNode As Node = importer.ImportNode(srcNode, True)

            ' Insert new node after the reference node.
            dstStory.InsertAfter(newNode, insertAfterNode)
            insertAfterNode = newNode
        Next srcNode
    Next srcSection
End Sub

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.

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

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)
    paragraph.ListFormat.RemoveNumbers();
[Visual Basic]

Dim body As Body = doc.FirstSection.Body

For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.RemoveNumbers()
Next paragraph
Applies list formatting of an existing list to a collection of paragraphs.
[C#]

Body body = doc.FirstSection.Body;
Aspose.Words.Lists.List list = doc.Lists[0];
foreach (Paragraph paragraph in body.Paragraphs)
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 2;
}
[Visual Basic]

Dim body As Body = doc.FirstSection.Body
Dim list As Aspose.Words.Lists.List = doc.Lists(0)
For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.List = list
    paragraph.ListFormat.ListLevelNumber = 2
Next paragraph
Creates new list formatting and applies it to a collection of paragraphs.
[C#]

Aspose.Words.Lists.List list = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot);

Body body = doc.FirstSection.Body;
foreach (Paragraph paragraph in body.Paragraphs)
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 1;
}
[Visual Basic]

Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot)

Dim body As Body = doc.FirstSection.Body
For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.List = list
    paragraph.ListFormat.ListLevelNumber = 1
Next paragraph
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)
{
    if (para.ListFormat.IsListItem)
    {
        Console.WriteLine(string.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId));
        Console.WriteLine(para.GetText());
    }
}
[Visual Basic]

Dim paras As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
For Each para As Paragraph In paras
    If para.ListFormat.IsListItem Then
        Console.WriteLine(String.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId))
        Console.WriteLine(para.GetText())
    End If
Next para

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))
{
    // 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++;
    }

}
[Visual Basic]

Dim doc As New Document(MyDir & "Lists.PrintOutAllLists.doc")
doc.UpdateListLabels()
Dim listParaCount As Integer = 1

For Each paragraph As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 Then
        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.
        Dim paragraphText As String = paragraph.ToString(SaveFormat.Text).Trim()
        Console.WriteLine("Exported Text: " & paragraphText)

        Dim label As ListLabel = 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 += 1
    End If

Next paragraph

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a 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 CompositeNode) | 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.
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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

See Also

Paragraph Class | Aspose.Words Namespace


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


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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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

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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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();
[Visual Basic]

' You can use ToArray to return a typed array of nodes.
Dim paras() As Paragraph = 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 pargraph in the collection is not visited.
foreach (Paragraph para in builder.Document.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true))
{
    if (para.Range.Text.Contains("third"))
    {
        para.PreviousSibling.Remove();
        para.Remove();
    }
}
[Visual Basic]

Dim builder As 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 pargraph in the collection is not visited.
For Each para As Paragraph In builder.Document.FirstSection.Body.GetChildNodes(NodeType.Paragraph, True)
    If para.Range.Text.Contains("third") Then
        para.PreviousSibling.Remove()
        para.Remove()
    End If
Next para
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))
{
    if (para.Range.Text.Contains("third"))
    {
        // Enumeration will continue even after this node is removed.
        para.Remove();
    }
}
[Visual Basic]

Dim builder As 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.
For Each para As Paragraph In builder.Document.FirstSection.Body.GetChildNodes(NodeType.Paragraph, True)
    If para.Range.Text.Contains("third") Then
        ' Enumeration will continue even after this node is removed.
        para.Remove()
    End If
Next para

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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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

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.
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.
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.

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

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.
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.
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.

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 = System.Drawing.Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Specify font formatting
Dim font As Aspose.Words.Font = builder.Font
font.Size = 16
font.Bold = True
font.Color = System.Drawing.Color.Blue
font.Name = "Arial"
font.Underline = Underline.Dash

' Specify paragraph formatting
Dim paragraphFormat As ParagraphFormat = builder.ParagraphFormat
paragraphFormat.FirstLineIndent = 8
paragraphFormat.Alignment = ParagraphAlignment.Justify
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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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;}

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


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 = System.Drawing.Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Specify font formatting
Dim font As Aspose.Words.Font = builder.Font
font.Size = 16
font.Bold = True
font.Color = System.Drawing.Color.Blue
font.Name = "Arial"
font.Underline = Underline.Dash

' Specify paragraph formatting
Dim paragraphFormat As ParagraphFormat = builder.ParagraphFormat
paragraphFormat.FirstLineIndent = 8
paragraphFormat.Alignment = ParagraphAlignment.Justify
paragraphFormat.KeepTogether = True

builder.Writeln("A whole paragraph.")

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 = System.Drawing.Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Specify font formatting
Dim font As Aspose.Words.Font = builder.Font
font.Size = 16
font.Bold = True
font.Color = System.Drawing.Color.Blue
font.Name = "Arial"
font.Underline = Underline.Dash

' Specify paragraph formatting
Dim paragraphFormat As ParagraphFormat = builder.ParagraphFormat
paragraphFormat.FirstLineIndent = 8
paragraphFormat.Alignment = ParagraphAlignment.Justify
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))
    foreach (Paragraph para in cell.Paragraphs)
        if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
            para.ParagraphFormat.KeepWithNext = true;
[Visual Basic]

' 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.
For Each cell As Cell In table.GetChildNodes(NodeType.Cell, True)
    For Each para As Paragraph In cell.Paragraphs
        If Not(cell.ParentRow.IsLastRow AndAlso para.IsEndOfCell) Then
            para.ParagraphFormat.KeepWithNext = True
        End If
    Next para
Next cell
Shows how to append a document to another document while keeping the content from splitting across two pages.
[C#]

Document dstDoc = new Document(gDataDir + "TestFile.Destination.doc");
Document srcDoc =  new Document(gDataDir + "TestFile.Source.doc");

// Set the source document to appear straight after the destination document's content.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous;

// Iterate through all sections in the source document.
foreach(Paragraph para in srcDoc.GetChildNodes(NodeType.Paragraph, true))
{
    para.ParagraphFormat.KeepWithNext = true;
}

dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
dstDoc.Save(gDataDir + "TestDcc.KeepSourceTogether Out.doc");
[Visual Basic]

Dim dstDoc As New Document(gDataDir & "TestFile.Destination.doc")
Dim srcDoc As New Document(gDataDir & "TestFile.Source.doc")

' Set the source document to appear straight after the destination document's content.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous

' Iterate through all sections in the source document.
For Each para As Paragraph In srcDoc.GetChildNodes(NodeType.Paragraph, True)
    para.ParagraphFormat.KeepWithNext = True
Next para

dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting)
dstDoc.Save(gDataDir & "TestDcc.KeepSourceTogether Out.doc")

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.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph formatting properties
Dim paragraphFormat As 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.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph formatting properties
Dim paragraphFormat As 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 = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;

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

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph borders
Dim borders As BorderCollection = 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
Dim shading As Shading = builder.ParagraphFormat.Shading
shading.Texture = TextureIndex.TextureDiagonalCross
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral
shading.ForegroundPatternColor = System.Drawing.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.");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph formatting properties
Dim paragraphFormat As 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(MyDir + "Lists.ParagraphStyleBulleted Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a paragraph style and specify some formatting for it.
Dim style As 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(MyDir & "Lists.ParagraphStyleBulleted Out.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();
[Visual Basic]

' Use a blank document
Dim doc As New Document()

' Create a document builder to insert content with into document.
Dim builder As 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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))
{
    // 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(MyDir + "Document.TableOfContentsTabStops Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

' Iterate through all paragraphs in the document
For Each para As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 AndAlso para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9 Then
        ' Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        Dim tab As TabStop = 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)
    End If
Next para

doc.Save(MyDir & "Document.TableOfContentsTabStops Out.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


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


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(MyDir + "Section.Protect Out.doc");
[Visual Basic]

' Create a blank document
Dim doc As New Document()

' Insert two sections with some text
Dim builder As 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(MyDir & "Section.Protect Out.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;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim text As String = doc.Range.Text
Shows how to replace all occurrences of word "sad" to "bad".
[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.Range.Replace("sad", "bad", false, true);
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.Range.Replace("sad", "bad", False, True)
Shows how to replace with a custom evaluator.
[C#]

public void ReplaceWithEvaluator()
{
    Document doc = new Document(MyDir + "Range.ReplaceWithEvaluator.doc");
    doc.Range.Replace(new Regex("[s|m]ad"), new MyReplaceEvaluator(), true);
    doc.Save(MyDir + "Range.ReplaceWithEvaluator Out.doc");
}

private class MyReplaceEvaluator : IReplacingCallback
{
    /// <summary>
    /// This is called during a replace operation each time a match is found.
    /// This method appends a number to the match string and returns it as a replacement string.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        e.Replacement = e.Match.ToString() + mMatchNumber.ToString();
        mMatchNumber++;
        return ReplaceAction.Replace;
    }

    private int mMatchNumber;
}
[Visual Basic]

Public Sub ReplaceWithEvaluator()
    Dim doc As New Document(MyDir & "Range.ReplaceWithEvaluator.doc")
    doc.Range.Replace(New Regex("[s|m]ad"), New MyReplaceEvaluator(), True)
    doc.Save(MyDir & "Range.ReplaceWithEvaluator Out.doc")
End Sub

Private Class MyReplaceEvaluator
    Implements IReplacingCallback
    ''' <summary>
    ''' This is called during a replace operation each time a match is found.
    ''' This method appends a number to the match string and returns it as a replacement string.
    ''' </summary>
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        e.Replacement = e.Match.ToString() & mMatchNumber.ToString()
        mMatchNumber += 1
        Return ReplaceAction.Replace
    End Function

    Private mMatchNumber As Integer
End Class

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.
Replace | Overloaded. Replaces all occurrences of a specified string in this range, with another string.
ToDocument | Constructs a new fully formed document that contains the 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.";
[Visual Basic]

Dim doc As New Document(MyDir & "Bookmark.doc")

' Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Dim bookmark As Bookmark = doc.Range.Bookmarks("MyBookmark")

' Get the name and text of the bookmark.
Dim name As String = bookmark.Name
Dim text As String = 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;
[Visual Basic]

Dim doc As New Document(MyDir & "FormFields.doc")
Dim formFields As FormFieldCollection = 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;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim text As String = 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.
Replace | Overloaded. Replaces all occurrences of a specified string in this range, with another string.
ToDocument | Constructs a new fully formed document that contains the 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 a section from a Word document.

[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());
[Visual Basic]

' Open Word document.
Dim doc As 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


Replace Method

Aspose.Words

Range.Replace Method

Replaces all occurrences of a specified string in this range, with another string.

Overload List

Replaces all occurrences of a specified string with another string.

public int Replace(string,string,bool,bool);

Finds all occurrences of a character pattern specified by a regular expression and calls a user defined replace evaluator method.

public int Replace(Regex,IReplacingCallback,bool);

Replaces all occurrences of a character pattern specified by a regular expression with another string.

public int Replace(Regex,string);

See Also

Range Class | Aspose.Words Namespace


Range.Replace Method (String, String, Boolean, Boolean)

Replaces all occurrences of a specified string with another string.

[Visual Basic]
Overloads Public Function Replace( _
ByVal oldValue As String, _
ByVal newValue As String, _
ByVal isMatchCase As Boolean, _
ByVal isMatchWholeWord As Boolean _
) As Integer
[C#]
public int Replace(
string oldValue,
string newValue,
bool isMatchCase,
bool isMatchWholeWord
);

Parameters

oldValue
A string to be replaced.
newValue
A string to replace all occurrences of oldValue.
isMatchCase
True indicates case-sensitive comparison, false indicates case-insensitive comparision.
isMatchWholeWord
True indicates the oldValue must be a standalone word.

Return Value

The number of replacements made.

Remarks

An exception is thrown if a captured or replacement string contain one or more special characters: paragraph break, cell break, section break, field start, field separator, field end, inline picture, drawing object, footnote.

Example

Simple find and replace operation.

[C#]

// Open the document.
Document doc = new Document(MyDir + "Range.ReplaceSimple.doc");

// Check the document contains what we are about to test.
Console.WriteLine(doc.FirstSection.Body.Paragraphs[0].GetText());

// Replace the text in the document.
doc.Range.Replace("_CustomerName_", "James Bond", false, false);

// Save the modified document.
doc.Save(MyDir + "Range.ReplaceSimple Out.doc");
[Visual Basic]

' Open the document.
Dim doc As New Document(MyDir & "Range.ReplaceSimple.doc")

' Check the document contains what we are about to test.
Console.WriteLine(doc.FirstSection.Body.Paragraphs(0).GetText())

' Replace the text in the document.
doc.Range.Replace("_CustomerName_", "James Bond", False, False)

' Save the modified document.
doc.Save(MyDir & "Range.ReplaceSimple Out.doc")
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];
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", false, false);

doc.Save(MyDir + "HeaderFooter.ReplaceText Out.doc");
[Visual Basic]

' Open the template document, containing obsolete copyright information in the footer.
Dim doc As New Document(MyDir & "HeaderFooter.ReplaceText.doc")

Dim headersFooters As HeaderFooterCollection = doc.FirstSection.HeadersFooters
Dim footer As HeaderFooter = headersFooters(HeaderFooterType.FooterPrimary)
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", False, False)

doc.Save(MyDir & "HeaderFooter.ReplaceText Out.doc")
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);

// Replace any instances of our string in the entire table.
table.Range.Replace("Carrots", "Eggs", true, true);
// Replace any instances of our string in the last cell of the table only.
table.LastRow.LastCell.Range.Replace("50", "20", true, true);

doc.Save(MyDir + "Table.ReplaceCellText Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.SimpleTable.doc")

' Get the first table in the document.
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Replace any instances of our string in the entire table.
table.Range.Replace("Carrots", "Eggs", True, True)
' Replace any instances of our string in the last cell of the table only.
table.LastRow.LastCell.Range.Replace("50", "20", True, True)

doc.Save(MyDir & "Table.ReplaceCellText Out.doc")

See Also

Range Class | Aspose.Words Namespace | Range.Replace Overload List


Range.Replace Method (Regex, IReplacingCallback, Boolean)

Finds all occurrences of a character pattern specified by a regular expression and calls a user defined replace evaluator method.

[Visual Basic]
Overloads Public Function Replace( _
ByVal pattern As Regex, _
ByVal handler As IReplacingCallback, _
ByVal isForward As Boolean _
) As Integer
[C#]
public int Replace(
Regex pattern,
IReplacingCallback handler,
bool isForward
);

Parameters

pattern
A regular expression pattern used to find matches.
handler
The user-defined method which evaluates replacement at each step.
isForward
True to replace from the beginning of the range to the end.

Return Value

The number of replacements made.

Remarks

An exception is thrown if a captured or replacement string contain one or more special characters: paragraph break, cell break, section break, field start, field separator, field end, inline picture, drawing object, footnote.

Example

Shows how to insert content of one document into another during a customized find and replace operation.

[C#]

public void InsertDocumentAtReplace()
{
    Document mainDoc = new Document(MyDir + "InsertDocument1.doc");
    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false);
    mainDoc.Save(MyDir + "InsertDocumentAtReplace Out.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph)e.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
[Visual Basic]

Public Sub InsertDocumentAtReplace()
    Dim mainDoc As New Document(MyDir & "InsertDocument1.doc")
    mainDoc.Range.Replace(New Regex("\[MY_DOCUMENT\]"), New InsertDocumentAtReplaceHandler(), False)
    mainDoc.Save(MyDir & "InsertDocumentAtReplace Out.doc")
End Sub

Private Class InsertDocumentAtReplaceHandler
    Implements IReplacingCallback
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim subDoc As New Document(MyDir & "InsertDocument2.doc")

        ' Insert a document after the paragraph, containing the match text.
        Dim para As Paragraph = CType(e.MatchNode.ParentNode, Paragraph)
        InsertDocument(para, subDoc)

        ' Remove the paragraph with the match text.
        para.Remove()

        Return ReplaceAction.Skip
    End Function
End Class
Replaces text specified with regular expression with HTML.
[C#]

public void ReplaceWithInsertHtml()
{
    // Open the document.
    Document doc = new Document(MyDir + "Range.ReplaceWithInsertHtml.doc");

    doc.Range.Replace(new Regex(@"<CustomerName>"), new ReplaceWithHtmlEvaluator(), false);

    // Save the modified document.
    doc.Save(MyDir + "Range.ReplaceWithInsertHtml Out.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    /// <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 e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>");

        e.Replacement = "";
        return ReplaceAction.Replace;
    }
}
[Visual Basic]

Public Sub ReplaceWithInsertHtml()
    ' Open the document.
    Dim doc As New Document(MyDir & "Range.ReplaceWithInsertHtml.doc")

    doc.Range.Replace(New Regex("<CustomerName>"), New ReplaceWithHtmlEvaluator(), False)

    ' Save the modified document.
    doc.Save(MyDir & "Range.ReplaceWithInsertHtml Out.doc")

End Sub

Private Class ReplaceWithHtmlEvaluator
    Implements IReplacingCallback
    ''' <summary>
    ''' NOTE: This is a simplistic method that will only work well when the match
    ''' starts at the beginning of a run.
    ''' </summary>
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim builder As New DocumentBuilder(CType(e.MatchNode.Document, Document))
        builder.MoveTo(e.MatchNode)
        ' Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>")

        e.Replacement = ""
        Return ReplaceAction.Replace
    End Function
End Class

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 oldValue.

Return Value

The number of replacements made.

Remarks

Replaces the whole match captured by the regular expression.

An exception is thrown if a captured or replacement string contain one or more special characters: paragraph break, cell break, section break, field start, field separator, field end, inline picture, drawing object, footnote.

Example

Shows how to replace all occurrences of words "sad" or "mad" to "bad".

[C#]

Document doc = new Document(MyDir + "Document.doc");
doc.Range.Replace(new Regex("[s|m]ad"), "bad");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.Range.Replace(New Regex("[s|m]ad"), "bad")

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.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();
[Visual Basic]

doc.FirstSection.Body.Range.UpdateFields()

See Also

Range Class | Aspose.Words 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#]

public void InsertDocumentAtReplace()
{
    Document mainDoc = new Document(MyDir + "InsertDocument1.doc");
    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false);
    mainDoc.Save(MyDir + "InsertDocumentAtReplace Out.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph)e.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
[Visual Basic]

Public Sub InsertDocumentAtReplace()
    Dim mainDoc As New Document(MyDir & "InsertDocument1.doc")
    mainDoc.Range.Replace(New Regex("\[MY_DOCUMENT\]"), New InsertDocumentAtReplaceHandler(), False)
    mainDoc.Save(MyDir & "InsertDocumentAtReplace Out.doc")
End Sub

Private Class InsertDocumentAtReplaceHandler
    Implements IReplacingCallback
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim subDoc As New Document(MyDir & "InsertDocument2.doc")

        ' Insert a document after the paragraph, containing the match text.
        Dim para As Paragraph = CType(e.MatchNode.ParentNode, Paragraph)
        InsertDocument(para, subDoc)

        ' Remove the paragraph with the match text.
        para.Remove()

        Return ReplaceAction.Skip
    End Function
End Class

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

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

See Also

Aspose.Words 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.ReplacingArgs

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

Remarks

Example

Shows how to insert content of one document into another during a customized find and replace operation.

[C#]

public void InsertDocumentAtReplace()
{
    Document mainDoc = new Document(MyDir + "InsertDocument1.doc");
    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false);
    mainDoc.Save(MyDir + "InsertDocumentAtReplace Out.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph)e.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
[Visual Basic]

Public Sub InsertDocumentAtReplace()
    Dim mainDoc As New Document(MyDir & "InsertDocument1.doc")
    mainDoc.Range.Replace(New Regex("\[MY_DOCUMENT\]"), New InsertDocumentAtReplaceHandler(), False)
    mainDoc.Save(MyDir & "InsertDocumentAtReplace Out.doc")
End Sub

Private Class InsertDocumentAtReplaceHandler
    Implements IReplacingCallback
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim subDoc As New Document(MyDir & "InsertDocument2.doc")

        ' Insert a document after the paragraph, containing the match text.
        Dim para As Paragraph = CType(e.MatchNode.ParentNode, Paragraph)
        InsertDocument(para, subDoc)

        ' Remove the paragraph with the match text.
        para.Remove()

        Return ReplaceAction.Skip
    End Function
End Class
Replaces text specified with regular expression with HTML.
[C#]

public void ReplaceWithInsertHtml()
{
    // Open the document.
    Document doc = new Document(MyDir + "Range.ReplaceWithInsertHtml.doc");

    doc.Range.Replace(new Regex(@"<CustomerName>"), new ReplaceWithHtmlEvaluator(), false);

    // Save the modified document.
    doc.Save(MyDir + "Range.ReplaceWithInsertHtml Out.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    /// <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 e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>");

        e.Replacement = "";
        return ReplaceAction.Replace;
    }
}
[Visual Basic]

Public Sub ReplaceWithInsertHtml()
    ' Open the document.
    Dim doc As New Document(MyDir & "Range.ReplaceWithInsertHtml.doc")

    doc.Range.Replace(New Regex("<CustomerName>"), New ReplaceWithHtmlEvaluator(), False)

    ' Save the modified document.
    doc.Save(MyDir & "Range.ReplaceWithInsertHtml Out.doc")

End Sub

Private Class ReplaceWithHtmlEvaluator
    Implements IReplacingCallback
    ''' <summary>
    ''' NOTE: This is a simplistic method that will only work well when the match
    ''' starts at the beginning of a run.
    ''' </summary>
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim builder As New DocumentBuilder(CType(e.MatchNode.Document, Document))
        builder.MoveTo(e.MatchNode)
        ' Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>")

        e.Replacement = ""
        Return ReplaceAction.Replace
    End Function
End Class

Requirements

Namespace: Aspose.Words

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

See Also

ReplacingArgs Members | Aspose.Words 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 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 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 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 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.

Example

Shows how to replace with a custom evaluator.

[C#]

public void ReplaceWithEvaluator()
{
    Document doc = new Document(MyDir + "Range.ReplaceWithEvaluator.doc");
    doc.Range.Replace(new Regex("[s|m]ad"), new MyReplaceEvaluator(), true);
    doc.Save(MyDir + "Range.ReplaceWithEvaluator Out.doc");
}

private class MyReplaceEvaluator : IReplacingCallback
{
    /// <summary>
    /// This is called during a replace operation each time a match is found.
    /// This method appends a number to the match string and returns it as a replacement string.
    /// </summary>
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        e.Replacement = e.Match.ToString() + mMatchNumber.ToString();
        mMatchNumber++;
        return ReplaceAction.Replace;
    }

    private int mMatchNumber;
}
[Visual Basic]

Public Sub ReplaceWithEvaluator()
    Dim doc As New Document(MyDir & "Range.ReplaceWithEvaluator.doc")
    doc.Range.Replace(New Regex("[s|m]ad"), New MyReplaceEvaluator(), True)
    doc.Save(MyDir & "Range.ReplaceWithEvaluator Out.doc")
End Sub

Private Class MyReplaceEvaluator
    Implements IReplacingCallback
    ''' <summary>
    ''' This is called during a replace operation each time a match is found.
    ''' This method appends a number to the match string and returns it as a replacement string.
    ''' </summary>
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        e.Replacement = e.Match.ToString() & mMatchNumber.ToString()
        mMatchNumber += 1
        Return ReplaceAction.Replace
    End Function

    Private mMatchNumber As Integer
End Class

See Also

ReplacingArgs Class | Aspose.Words 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#]

public void InsertDocumentAtReplace()
{
    Document mainDoc = new Document(MyDir + "InsertDocument1.doc");
    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false);
    mainDoc.Save(MyDir + "InsertDocumentAtReplace Out.doc");
}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        Document subDoc = new Document(MyDir + "InsertDocument2.doc");

        // Insert a document after the paragraph, containing the match text.
        Paragraph para = (Paragraph)e.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text.
        para.Remove();

        return ReplaceAction.Skip;
    }
}
[Visual Basic]

Public Sub InsertDocumentAtReplace()
    Dim mainDoc As New Document(MyDir & "InsertDocument1.doc")
    mainDoc.Range.Replace(New Regex("\[MY_DOCUMENT\]"), New InsertDocumentAtReplaceHandler(), False)
    mainDoc.Save(MyDir & "InsertDocumentAtReplace Out.doc")
End Sub

Private Class InsertDocumentAtReplaceHandler
    Implements IReplacingCallback
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim subDoc As New Document(MyDir & "InsertDocument2.doc")

        ' Insert a document after the paragraph, containing the match text.
        Dim para As Paragraph = CType(e.MatchNode.ParentNode, Paragraph)
        InsertDocument(para, subDoc)

        ' Remove the paragraph with the match text.
        para.Remove()

        Return ReplaceAction.Skip
    End Function
End Class

See Also

ReplacingArgs Class | Aspose.Words 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 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#]

public void ReplaceWithInsertHtml()
{
    // Open the document.
    Document doc = new Document(MyDir + "Range.ReplaceWithInsertHtml.doc");

    doc.Range.Replace(new Regex(@"<CustomerName>"), new ReplaceWithHtmlEvaluator(), false);

    // Save the modified document.
    doc.Save(MyDir + "Range.ReplaceWithInsertHtml Out.doc");

}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    /// <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 e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        // Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>");

        e.Replacement = "";
        return ReplaceAction.Replace;
    }
}
[Visual Basic]

Public Sub ReplaceWithInsertHtml()
    ' Open the document.
    Dim doc As New Document(MyDir & "Range.ReplaceWithInsertHtml.doc")

    doc.Range.Replace(New Regex("<CustomerName>"), New ReplaceWithHtmlEvaluator(), False)

    ' Save the modified document.
    doc.Save(MyDir & "Range.ReplaceWithInsertHtml Out.doc")

End Sub

Private Class ReplaceWithHtmlEvaluator
    Implements IReplacingCallback
    ''' <summary>
    ''' NOTE: This is a simplistic method that will only work well when the match
    ''' starts at the beginning of a run.
    ''' </summary>
    Private Function IReplacingCallback_Replacing(ByVal e As ReplacingArgs) As ReplaceAction Implements IReplacingCallback.Replacing
        Dim builder As New DocumentBuilder(CType(e.MatchNode.Document, Document))
        builder.MoveTo(e.MatchNode)
        ' Replace '<CustomerName>' text with a red bold name.
        builder.InsertHtml("<b><font color='red'>James Bond</font></b>")

        e.Replacement = ""
        Return ReplaceAction.Replace
    End Function
End Class

See Also

ReplacingArgs 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.
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.
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


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
[C#]
public class RevisionCollection : 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.
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.
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


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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.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


RevisionType Enumeration

Specifies the type of change being tracked in Revision.

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

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


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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Create a new run of text.
Dim run As New Run(doc, "Hello")

' Specify character formatting for the run of text.
Dim f As Aspose.Words.Font = 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)
{
    // 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);
[Visual Basic]

Dim doc As New Document(MyDir & "Font.Names.doc")

' Select all runs in the document.
Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)

' Use a hashtable so we will keep only unique font names.
Dim fontNames As New Hashtable()

For Each run As Run In runs
    ' 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) = Nothing
Next run

' 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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.
IsInsertRevision (inherited from Inline) | Returns true if this object was 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Create a new run of text.
Dim run As New Run(doc, "Hello")

' Specify character formatting for the run of text.
Dim f As Aspose.Words.Font = 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.
IsInsertRevision (inherited from Inline) | Returns true if this object was 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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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(MyDir + "Document.ConvertToHtml Out.html", SaveFormat.Html);
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

doc.Save(MyDir & "Document.ConvertToHtml Out.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
Swf | Saves the document in the SWF (Adobe Flash Player) format. | 43
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
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
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

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]
Public Class Section
Inherits CompositeNode
[C#]
public 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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. Creates a duplicate of the node.
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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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)
{
    // 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());
[Visual Basic]

' Open a document.
Dim doc As 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.
For Each section As Section In doc.Sections
    ' Each section has a Body node that contains main story (main text) of the section.
    Dim body As 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()
Next section

' 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];
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", false, false);

doc.Save(MyDir + "HeaderFooter.ReplaceText Out.doc");
[Visual Basic]

' Open the template document, containing obsolete copyright information in the footer.
Dim doc As New Document(MyDir & "HeaderFooter.ReplaceText.doc")

Dim headersFooters As HeaderFooterCollection = doc.FirstSection.HeadersFooters
Dim footer As HeaderFooter = headersFooters(HeaderFooterType.FooterPrimary)
footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", False, False)

doc.Save(MyDir & "HeaderFooter.ReplaceText Out.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)
{
    // 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;

    footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
    if (footer != null)
        footer.Remove();

    // Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
    if (footer != null)
        footer.Remove();

    footer = section.HeadersFooters[HeaderFooterType.FooterEven];
    if (footer != null)
        footer.Remove();
}

doc.Save(MyDir + "HeaderFooter.RemoveFooters Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "HeaderFooter.RemoveFooters.doc")

For Each section As Section In doc
    ' Up to three different footers are possible in a section (for first, even and odd pages).
    ' We check and delete all of them.
    Dim footer As HeaderFooter

    footer = section.HeadersFooters(HeaderFooterType.FooterFirst)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    ' Primary footer is the footer used for odd pages.
    footer = section.HeadersFooters(HeaderFooterType.FooterPrimary)
    If footer IsNot Nothing Then
        footer.Remove()
    End If

    footer = section.HeadersFooters(HeaderFooterType.FooterEven)
    If footer IsNot Nothing Then
        footer.Remove()
    End If
Next section

doc.Save(MyDir & "HeaderFooter.RemoveFooters Out.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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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 = System.Drawing.Color.Blue;
border.DistanceFromText = 0;

doc.Save(MyDir + "PageSetup.PageBorderTop Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim ps As PageSetup = doc.Sections(0).PageSetup
ps.BorderAlwaysInFront = False
ps.BorderDistanceFrom = PageBorderDistanceFrom.PageEdge
ps.BorderAppliesTo = PageBorderAppliesTo.FirstPage

Dim border As Border = ps.Borders(BorderType.Top)
border.LineStyle = LineStyle.Single
border.LineWidth = 30
border.Color = System.Drawing.Color.Blue
border.DistanceFromText = 0

doc.Save(MyDir & "PageSetup.PageBorderTop Out.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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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(MyDir + "Section.Protect Out.doc");
[Visual Basic]

' Create a blank document
Dim doc As New Document()

' Insert two sections with some text
Dim builder As 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(MyDir & "Section.Protect Out.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. Creates a duplicate of the node.
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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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);
[Visual Basic]

Dim doc As New Document(MyDir & "Section.AppendContent.doc")

' This is the section that we will append and prepend to.
Dim section As Section = doc.Sections(2)

' This copies content of the 1st section and inserts it at the beginning of the specified section.
Dim sectionToPrepend As Section = doc.Sections(0)
section.PrependContent(sectionToPrepend)

' This copies content of the 2nd section and inserts it at the end of the specified section.
Dim sectionToAppend As Section = 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();
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim section As 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();
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim section As 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());
[Visual Basic]

' Open the document.
Dim doc As 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.
Dim lastSectionIdx As Integer = doc.Sections.Count - 1
Dim newSection As Section = 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();
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim section As 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();
[Visual Basic]

' Create a blank document
Dim doc As New Document()
Dim section As 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);
[Visual Basic]

Dim doc As New Document(MyDir & "Section.AppendContent.doc")

' This is the section that we will append and prepend to.
Dim section As Section = doc.Sections(2)

' This copies content of the 1st section and inserts it at the beginning of the specified section.
Dim sectionToPrepend As Section = doc.Sections(0)
section.PrependContent(sectionToPrepend)

' This copies content of the 2nd section and inserts it at the end of the specified section.
Dim sectionToAppend As Section = 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());
[Visual Basic]

' Open the document.
Dim doc As 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.
Dim lastSectionIdx As Integer = doc.Sections.Count - 1
Dim newSection As Section = 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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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];
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
Dim section As 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(MyDir + "Rendering.UpdatePageLayout1 Out.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(MyDir + "Rendering.UpdatePageLayout2 Out.pdf");
[Visual Basic]

Dim doc As 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(MyDir & "Rendering.UpdatePageLayout1 Out.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(MyDir & "Rendering.UpdatePageLayout2 Out.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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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


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;
[Visual Basic]

Dim doc As 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 = System.Drawing.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", doc.GetText());

// Save the document.
doc.Save(MyDir + "Section.CreateFromScratch Out.doc");
[Visual Basic]

' Create an "empty" document. Note that like in Microsoft Word,
' the empty document has one section, body and one paragraph in it.
Dim doc As 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.
Dim section As 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.
Dim body As 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.
Dim para As 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.
Dim run As New Run(doc)
run.Text = "Hello World!"
run.Font.Color = System.Drawing.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!" & Constants.vbFormFeed, doc.GetText())

' Save the document.
doc.Save(MyDir & "Section.CreateFromScratch Out.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.Shading

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

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 = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;

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

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph borders
Dim borders As BorderCollection = 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
Dim shading As Shading = builder.ParagraphFormat.Shading
shading.Texture = TextureIndex.TextureDiagonalCross
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral
shading.ForegroundPatternColor = System.Drawing.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(MyDir + "Table.SetBordersAndShading Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir & "Table.SetBordersAndShading Out.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 = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;

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

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph borders
Dim borders As BorderCollection = 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
Dim shading As Shading = builder.ParagraphFormat.Shading
shading.Texture = TextureIndex.TextureDiagonalCross
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral
shading.ForegroundPatternColor = System.Drawing.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(MyDir + "Table.SetBordersAndShading Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir & "Table.SetBordersAndShading Out.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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.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 = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;

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

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph borders
Dim borders As BorderCollection = 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
Dim shading As Shading = builder.ParagraphFormat.Shading
shading.Texture = TextureIndex.TextureDiagonalCross
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral
shading.ForegroundPatternColor = System.Drawing.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 = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;

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

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph borders
Dim borders As BorderCollection = 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
Dim shading As Shading = builder.ParagraphFormat.Shading
shading.Texture = TextureIndex.TextureDiagonalCross
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral
shading.ForegroundPatternColor = System.Drawing.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


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#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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.
IsInsertRevision (inherited from Inline) | Returns true if this object was 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
IsInsertRevision (inherited from Inline) | Returns true if this object was 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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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);
[Visual Basic]

' Create an empty document. It contains one empty paragraph.
Dim doc As New Document()

' Create a new run of text.
Dim run As New Run(doc, "Hello")

' Specify character formatting for the run of text.
Dim f As Aspose.Words.Font = 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(MyDir + "Shape.CreateTextBox Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()

' Create a new shape of type TextBox
Dim textBox As 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))
Dim para As Paragraph = textBox.FirstParagraph
para.ParagraphFormat.Alignment = ParagraphAlignment.Center

' Add some text to the paragraph.
Dim run As 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(MyDir & "Shape.CreateTextBox Out.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);
[Visual Basic]

Dim doc As New Document(MyDir & "DocumentBuilder.doc")
Dim builder As 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)
{
    // Quick typed access to the first row of the table.
    if (table.FirstRow != null)
        table.FirstRow.Remove();

    // Quick typed access to the last row of the table.
    if (table.LastRow != null)
        table.LastRow.Remove();
}
[Visual Basic]

' Quick typed access to the first child Section node of the Document.
Dim section As Section = doc.FirstSection

' Quick typed access to the Body child node of the Section.
Dim body As Body = section.Body

' Quick typed access to all Table child nodes contained in the Body.
Dim tables As TableCollection = body.Tables

For Each table As Table In tables
    ' Quick typed access to the first row of the table.
    If table.FirstRow IsNot Nothing Then
        table.FirstRow.Remove()
    End If

    ' Quick typed access to the last row of the table.
    If table.LastRow IsNot Nothing Then
        table.LastRow.Remove()
    End If
Next table

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 footer using the document object model and inserts it into a section.

[C#]

Document doc = new Document();

HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
doc.FirstSection.HeadersFooters.Add(footer);

// Add a paragraph with text to the footer.
footer.AppendParagraph("TEST FOOTER");

doc.Save(MyDir + "HeaderFooter.CreateFooter Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim footer As New HeaderFooter(doc, HeaderFooterType.FooterPrimary)
doc.FirstSection.HeadersFooters.Add(footer)

' Add a paragraph with text to the footer.
footer.AppendParagraph("TEST FOOTER")

doc.Save(MyDir & "HeaderFooter.CreateFooter Out.doc")

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
EndnoteSeparator | Contains the text of the endnote separator, represented by FootnoteSeparator. | 14
EndnoteContinuationSeparator | Contains the text of the endnote continuation separator, represented by FootnoteSeparator. | 15

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";
    }
}
[Visual Basic]

Dim doc As New Document()
For Each style As Style In doc.Styles
    If style.Font IsNot Nothing Then
        style.Font.ClearFormatting()
        style.Font.Size = 20
        style.Font.Name = "Arial"
    End If
Next style
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(MyDir + "Lists.ParagraphStyleBulleted Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a paragraph style and specify some formatting for it.
Dim style As 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(MyDir & "Lists.ParagraphStyleBulleted Out.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

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.
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

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.
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


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)
{
    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(MyDir + "Font.Style Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Font.Style.doc")

' Select all run nodes in the document.
Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)

' Loop through every run node.
For Each run As Run In runs
    Dim charStyle As Style = run.Font.Style

    ' If the style of the run is not a built-in character style, apply double underline.
    If (Not charStyle.BuiltIn) Then
        run.Font.Underline = Underline.Double
    End If
Next run

doc.Save(MyDir & "Font.Style Out.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";
    }
}
[Visual Basic]

Dim doc As New Document()
For Each style As Style In doc.Styles
    If style.Font IsNot Nothing Then
        style.Font.ClearFormatting()
        style.Font.Size = 20
        style.Font.Name = "Arial"
    End If
Next style
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(MyDir + "Lists.ParagraphStyleBulleted Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a paragraph style and specify some formatting for it.
Dim style As 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(MyDir & "Lists.ParagraphStyleBulleted Out.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


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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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(MyDir + "Lists.ParagraphStyleBulleted Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a paragraph style and specify some formatting for it.
Dim style As 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(MyDir & "Lists.ParagraphStyleBulleted Out.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);
[Visual Basic]

Dim doc As New Document()
Dim styles As StyleCollection = doc.Styles

For Each style As Style In styles
    Console.WriteLine(style.Name)
Next style
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";
[Visual Basic]

' The AddCopy method creates a copy of the specified style and automatically generates a new name for the style, such as "Heading 1_0".
Dim newStyle As Style = 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(MyDir + "Lists.ParagraphStyleBulleted Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a paragraph style and specify some formatting for it.
Dim style As 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(MyDir & "Lists.ParagraphStyleBulleted Out.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))
{
    // 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(MyDir + "Document.TableOfContentsTabStops Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

' Iterate through all paragraphs in the document
For Each para As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 AndAlso para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9 Then
        ' Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        Dim tab As TabStop = 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)
    End If
Next para

doc.Save(MyDir & "Document.TableOfContentsTabStops Out.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.

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
[C#]
public class StyleCollection : 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(MyDir + "Lists.ParagraphStyleBulleted Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a paragraph style and specify some formatting for it.
Dim style As 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(MyDir & "Lists.ParagraphStyleBulleted Out.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.
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.
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


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(MyDir + "Rendering.UpdatePageLayout1 Out.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(MyDir + "Rendering.UpdatePageLayout2 Out.pdf");
[Visual Basic]

Dim doc As 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(MyDir & "Rendering.UpdatePageLayout1 Out.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(MyDir & "Rendering.UpdatePageLayout2 Out.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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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";
[Visual Basic]

' The AddCopy method creates a copy of the specified style and automatically generates a new name for the style, such as "Heading 1_0".
Dim newStyle As Style = 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);
[Visual Basic]

' This is the style in the source document to copy to the destination document.
Dim srcStyle As Style = 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.
Dim newStyle As Style = dstDoc.Styles.AddCopy(srcStyle)
Demonstrates how to copy a style from one document to another and overide 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";
[Visual Basic]

' This is the style in the source document to copy to the destination document.
Dim srcStyle As Style = 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.
Dim newStyle As Style = 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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.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)
{
    // 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(MyDir + "Font.StyleIdentifier Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Font.StyleIdentifier.doc")

' Select all run nodes in the document.
Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)

' Loop through every run node.
For Each run As Run In runs
    ' 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) Then
        run.Font.StyleIdentifier = StyleIdentifier.Strong
    End If
Next run

doc.Save(MyDir & "Font.StyleIdentifier Out.doc")
Shows how to import the data from a DataTable and insert it into a new table in the document.
[C#]

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

// We can position where we want the table to be inserted and also specify any extra formatting to be
// applied onto the table as well.
DocumentBuilder builder = new DocumentBuilder(doc);

// We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape;

// Retrieve the data from our data source which is stored as a DataTable.
DataTable dataTable = GetEmployees(databaseDir);

// Build a table in the document from the data contained in the DataTable.
Table table = ImportTableFromDataTable(builder, dataTable, true);

// We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1;
table.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.RowBands | TableStyleOptions.LastColumn;

// For our table we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren();

doc.Save(dataDir + "Table.FromDataTable Out.docx");
[Visual Basic]

' Create a new document.
Dim doc As New Document()

' We can position where we want the table to be inserted and also specify any extra formatting to be
' applied onto the table as well.
Dim builder As New DocumentBuilder(doc)

' We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape

' Retrieve the data from our data source which is stored as a DataTable.
Dim dataTable As DataTable = GetEmployees(databaseDir)

' Build a table in the document from the data contained in the DataTable.
Dim table As Table = ImportTableFromDataTable(builder, dataTable, True)

' We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1
table.StyleOptions = TableStyleOptions.FirstRow Or TableStyleOptions.RowBands Or TableStyleOptions.LastColumn

' For our table we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren()

doc.Save(dataDir & "Table.FromDataTable Out.docx")

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
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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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

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

BaseStyleName (inherited from Style) | Gets/sets the name of the style this style is based on.
BuiltIn (inherited from Style) | True if this style is one of the built-in styles in MS Word.
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.
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.
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.
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 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]
Public Class TabStop
[C#]
public 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))
{
    // 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(MyDir + "Document.TableOfContentsTabStops Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

' Iterate through all paragraphs in the document
For Each para As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 AndAlso para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9 Then
        ' Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        Dim tab As TabStop = 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)
    End If
Next para

doc.Save(MyDir & "Document.TableOfContentsTabStops Out.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))
{
    // 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(MyDir + "Document.TableOfContentsTabStops Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

' Iterate through all paragraphs in the document
For Each para As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 AndAlso para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9 Then
        ' Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        Dim tab As TabStop = 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)
    End If
Next para

doc.Save(MyDir & "Document.TableOfContentsTabStops Out.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))
{
    // 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(MyDir + "Document.TableOfContentsTabStops Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

' Iterate through all paragraphs in the document
For Each para As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 AndAlso para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9 Then
        ' Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        Dim tab As TabStop = 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)
    End If
Next para

doc.Save(MyDir & "Document.TableOfContentsTabStops Out.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))
{
    // 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(MyDir + "Document.TableOfContentsTabStops Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

' Iterate through all paragraphs in the document
For Each para As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 AndAlso para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9 Then
        ' Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        Dim tab As TabStop = 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)
    End If
Next para

doc.Save(MyDir & "Document.TableOfContentsTabStops Out.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.TabStopCollection

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

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.

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.

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();

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
);

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.

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.

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))
{
    // 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(MyDir + "Document.TableOfContentsTabStops Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

' Iterate through all paragraphs in the document
For Each para As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 AndAlso para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9 Then
        ' Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
        Dim tab As TabStop = 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)
    End If
Next para

doc.Save(MyDir & "Document.TableOfContentsTabStops Out.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(MyDir + "PageSetup.ColumnsCustomWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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.
Dim c1 As TextColumn = columns(0)
c1.Width = 100
c1.SpaceAfter = 20

' Set the second column to take the rest of the space available on the page.
Dim c2 As TextColumn = columns(1)
Dim ps As PageSetup = builder.PageSetup
Dim contentWidth As Double = 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(MyDir & "PageSetup.ColumnsCustomWidth Out.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(MyDir + "PageSetup.ColumnsCustomWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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.
Dim c1 As TextColumn = columns(0)
c1.Width = 100
c1.SpaceAfter = 20

' Set the second column to take the rest of the space available on the page.
Dim c2 As TextColumn = columns(1)
Dim ps As PageSetup = builder.PageSetup
Dim contentWidth As Double = 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(MyDir & "PageSetup.ColumnsCustomWidth Out.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(MyDir + "PageSetup.ColumnsCustomWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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.
Dim c1 As TextColumn = columns(0)
c1.Width = 100
c1.SpaceAfter = 20

' Set the second column to take the rest of the space available on the page.
Dim c2 As TextColumn = columns(1)
Dim ps As PageSetup = builder.PageSetup
Dim contentWidth As Double = 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(MyDir & "PageSetup.ColumnsCustomWidth Out.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(MyDir + "PageSetup.ColumnsSameWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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(MyDir & "PageSetup.ColumnsSameWidth Out.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(MyDir + "PageSetup.ColumnsCustomWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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.
Dim c1 As TextColumn = columns(0)
c1.Width = 100
c1.SpaceAfter = 20

' Set the second column to take the rest of the space available on the page.
Dim c2 As TextColumn = columns(1)
Dim ps As PageSetup = builder.PageSetup
Dim contentWidth As Double = 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(MyDir & "PageSetup.ColumnsCustomWidth Out.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(MyDir + "PageSetup.ColumnsCustomWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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.
Dim c1 As TextColumn = columns(0)
c1.Width = 100
c1.SpaceAfter = 20

' Set the second column to take the rest of the space available on the page.
Dim c2 As TextColumn = columns(1)
Dim ps As PageSetup = builder.PageSetup
Dim contentWidth As Double = 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(MyDir & "PageSetup.ColumnsCustomWidth Out.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(MyDir + "PageSetup.ColumnsCustomWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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.
Dim c1 As TextColumn = columns(0)
c1.Width = 100
c1.SpaceAfter = 20

' Set the second column to take the rest of the space available on the page.
Dim c2 As TextColumn = columns(1)
Dim ps As PageSetup = builder.PageSetup
Dim contentWidth As Double = 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(MyDir & "PageSetup.ColumnsCustomWidth Out.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(MyDir + "PageSetup.ColumnsSameWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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(MyDir & "PageSetup.ColumnsSameWidth Out.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(MyDir + "PageSetup.ColumnsSameWidth Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim columns As TextColumnCollection = 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(MyDir & "PageSetup.ColumnsSameWidth Out.doc")

See Also

TextColumnCollection Class | 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 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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

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 = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;

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

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Set paragraph borders
Dim borders As BorderCollection = 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
Dim shading As Shading = builder.ParagraphFormat.Shading
shading.Texture = TextureIndex.TextureDiagonalCross
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral
shading.ForegroundPatternColor = System.Drawing.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(MyDir + "Table.SetOutlineBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.EmptyTable.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' 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(MyDir & "Table.SetOutlineBorders Out.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


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(MyDir + "DocumentBuilder.InsertHyperlink Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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(MyDir & "DocumentBuilder.InsertHyperlink Out.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
[C#]
public class VariableCollection : 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 (DictionaryEntry entry in doc.Variables)
{
    string name = entry.Key.ToString();
    string value = entry.Value.ToString();

    // Do something useful.
    Console.WriteLine("Name: {0}, Value: {1}", name, value);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

For Each entry As DictionaryEntry In doc.Variables
    Dim name As String = entry.Key.ToString()
    Dim value As String = entry.Value.ToString()

    ' Do something useful.
    Console.WriteLine("Name: {0}, Value: {1}", name, value)
Next entry

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 a dictionary enumerator object that can be used to iterate over all items 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;}

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 a dictionary enumerator object that can be used to iterate over all items 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.

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();

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.

See Also

VariableCollection Class | Aspose.Words Namespace


VariableCollection.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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

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.

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.

See Also

VariableCollection 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#]

public void ToText()
{
    // 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()
    {
        mIsSkipText = false;
        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 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 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.
        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.
        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.
        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.
        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.
        mBuilder.Append("*** Body Started ***\r\n");

        return VisitorAction.Continue;
    }

    public override VisitorAction VisitBodyEnd(Body body)
    {
        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>
    /// Adds text to the current output. Honours the enabled/disabled output flag.
    /// </summary>
    private void AppendText(string text)
    {
        if (!mIsSkipText)
            mBuilder.Append(text);
    }

    private readonly StringBuilder mBuilder;
    private bool mIsSkipText;
}
[Visual Basic]

Public Sub ToText()
    ' Open the document we want to convert.
    Dim doc As New Document(MyDir & "Visitor.ToText.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim myConverter As 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())
End Sub

''' <summary>
''' Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
''' </summary>
Public Class MyDocToTxtWriter
    Inherits DocumentVisitor
    Public Sub New()
        mIsSkipText = False
        mBuilder = New StringBuilder()
    End Sub

    ''' <summary>
    ''' Gets the plain text of the document that was accumulated by the visitor.
    ''' </summary>
    Public Function GetText() As String
        Return mBuilder.ToString()
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        AppendText(run.Text)

        ' Let the visitor continue visiting other nodes.
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' 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.
        mIsSkipText = True

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        ' Once reached a field separator node, we enable the output because we are
        ' now entering the field result nodes.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        ' 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.
        mIsSkipText = False

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Paragraph node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphEnd(ByVal paragraph As Paragraph) As VisitorAction
        ' When outputting to plain text we output Cr+Lf characters.
        AppendText(ControlChar.CrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyStart(ByVal body As Body) As VisitorAction
        ' We can detect beginning and end of all composite nodes such as Section, Body,
        ' Table, Paragraph etc and provide custom handling for them.
        mBuilder.Append("*** Body Started ***" & Constants.vbCrLf)

        Return VisitorAction.Continue
    End Function

    Public Overrides Function VisitBodyEnd(ByVal body As Body) As VisitorAction
        mBuilder.Append("*** Body Ended ***" & Constants.vbCrLf)
        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a HeaderFooter node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitHeaderFooterStart(ByVal headerFooter As HeaderFooter) As VisitorAction
        ' 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
    End Function

    ''' <summary>
    ''' Adds text to the current output. Honours the enabled/disabled output flag.
    ''' </summary>
    Private Sub AppendText(ByVal text As String)
        If (Not mIsSkipText) Then
            mBuilder.Append(text)
        End If
    End Sub

    Private ReadOnly mBuilder As StringBuilder
    Private mIsSkipText As Boolean
End Class

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.

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;}

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;}

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 IEnumerable, IWarningCallback
[C#]
public class WarningInfoCollection : IEnumerable, IWarningCallback

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.

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 an instance of this 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 an instance of this 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();

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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

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
Swf | Module that renders SWF. | 6
Xps | Module that renders XPS. | 7
Pdf | Module that renders PDF. | 8
Image | Module that renders images. | 9
Docx | Module that reads/writes DOCX files. | 10
Doc | Module that reads/writes binary DOC files. | 11
Text | Module that reads/writes plaintext files. | 12
Rtf | Module that reads/writes RTF files. | 13
WordML | Module that reads/writes WML files. | 14
Nrx | Common modules that are shared between DOCX/WML reader/writer modules. | 15
Odt | Module that reads/writes ODT files. | 16
Html | Module that reads/writes HTML/MHTML files. | 17
Validator | Module that verifies model consistency and validity. | 18
Xaml | Module that reads/writes Xaml files. | 19

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.

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

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
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

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.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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;}

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.

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.

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.

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.

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.

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.

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.

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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;}

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.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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.

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.

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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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.

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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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.

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.

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.

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.

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 this 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.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace | Document | GlossaryDocument | BuildingBlock


GlossaryDocument Constructor

Initializes a new instance of this 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.

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;}

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.

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.

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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.

See Also

GlossaryDocument Class | Aspose.Words.BuildingBlocks Namespace


Aspose.Words.Drawing

Aspose.Words

Aspose.Words.Drawing Namespace

The Aspose.Words.Drawing namespace contains classes that allow to create and modify drawing objects in Microsoft Word documents.

Aspose.Words supports all drawing objects in Microsoft Word documents, including OfficeArt shapes, textboxes, pictures, diagrams, OLE objects and ActiveX controls.

The main classes in this namespace are:

  • Shape represents an object in the drawing layer, such as an AutoShape, textbox, freeform, OLE object, ActiveX control, or picture.
  • GroupShape represents a group of shapes in a document.
  • ShapeBase is the base class for the shape and group shape classes, provides all common shape properties such as position, size and text wrapping. A shape is a node in the document tree.

Although not every type of drawing object can be programmatically created and not every shape property can be accessed, all drawing objects are fully preserved in Microsoft Word documents during document open-save operations.

Names of classes, methods and properties in this namespace correspond to VML DOM where possible.

Namespace hierarchy

Classes

Class | Description
DrawingML | Represents a DrawingML shape, picture, chart or diagram in a document.
DrawingMLImageData | Defines an image for a DrawingML picture.
Fill | Defines a fill for a shape.
GroupShape | Represents a group of shapes in a document.
ImageData | Defines an image for a VML-based shape.
ImageSize | Contains information about image size and resolution.
OleFormat | Provides access to the data of an OLE object or ActiveX control.
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.
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).

Interfaces

Interface | Description
IImageData | Provides a common interface for manipulating images stored in VML-based and DrawingML-based shapes in a document.

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.
ShapeType | Specifies the type of shape in a Microsoft Word document.
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

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

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

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

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


DrawingML Class

Represents a DrawingML shape, picture, chart or diagram in a document.

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

System.Object
Aspose.Words.Node
Aspose.Words.Inline
Aspose.Words.Drawing.DrawingML

[Visual Basic]
Public Class DrawingML
Inherits Inline
[C#]
public class DrawingML : Inline

Remarks

In this version of Aspose.Words, DrawingML nodes do not provide public methods and properties to create or modify a DrawingML object. In this version you are not able to instantiate DrawingML nodes or modify existing except deleting them.

Support for DrawingML in Aspose.Words is currently limited to:

  • Roundtrip (fully preserve) DrawingML objects during DOCX open/save operations.
  • Preserve DrawingML pictures when converting a DOCX document into other formats.

DrawingML can only be a child of Paragraph.

Example

Shows how to render a DrawingML image independent of the document to a JPEG image on the disk.

[C#]

// Save the DrawingML image to disk in JPEG format and using default options.
drawingML.GetShapeRenderer().Save(dataDir + "TestFile.RenderDrawingML Out.jpg", null);
[Visual Basic]

' Save the DrawingML image to disk in JPEG format and using default options.
drawingML.GetShapeRenderer().Save(dataDir & "TestFile.RenderDrawingML Out.jpg", Nothing)

Requirements

Namespace: Aspose.Words.Drawing

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

See Also

DrawingML Members | Aspose.Words.Drawing Namespace


DrawingML Members

DrawingML overview

Public Instance Properties

AlternativeText | Gets or sets the alternative text (description) to be rendered when the graphics object cannot be rendered.
BehindText |
BoundsWithEffects | Gets final extent that DrawingML 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.
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.
HasImage | Returns true if the shape has image bytes or links an image.
Height | Gets or sets the height of the shape in points.
HRef | Gets or sets the full hyperlink address for a DrawingML.
ImageData | Provides access to the image of the shape. Returns null if the shape cannot have an image.
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.
IsInline | A quick way to determine if this DrawingML object is positioned inline with text.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
Name | Gets or sets the optional DrawingML name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.DrawingML.
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.
ScreenTip | Defines the text displayed when the mouse pointer moves over the DrawingML.
Size | Gets or sets the size of the shape in points.
Target | Gets or sets the target frame for the DrawingML hyperlink.
Width | Gets or sets the width of the shape in points.
ZOrder |

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) | Creates a duplicate of the node.
FetchInheritedShapeAttr | Reserved for system use. IShapeAttrSource.
FetchShapeAttr | Reserved for system use. IShapeAttrSource.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetDirectShapeAttr | Reserved for system use. IShapeAttrSource.
GetShapeRenderer | Creates and returns an object that can be used to render this shape into an image.
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.
RemoveShapeAttr | Reserved for system use. IShapeAttrSource.
SetShapeAttr | Reserved for system use. IShapeAttrSource.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML Properties

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

Public Instance Properties

AlternativeText | Gets or sets the alternative text (description) to be rendered when the graphics object cannot be rendered.
BehindText |
BoundsWithEffects | Gets final extent that DrawingML 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.
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.
HasImage | Returns true if the shape has image bytes or links an image.
Height | Gets or sets the height of the shape in points.
HRef | Gets or sets the full hyperlink address for a DrawingML.
ImageData | Provides access to the image of the shape. Returns null if the shape cannot have an image.
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.
IsInline | A quick way to determine if this DrawingML object is positioned inline with text.
IsInsertRevision (inherited from Inline) | Returns true if this object was inserted in Microsoft Word while change tracking was enabled.
Name | Gets or sets the optional DrawingML name.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.DrawingML.
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.
ScreenTip | Defines the text displayed when the mouse pointer moves over the DrawingML.
Size | Gets or sets the size of the shape in points.
Target | Gets or sets the target frame for the DrawingML hyperlink.
Width | Gets or sets the width of the shape in points.
ZOrder |

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


AlternativeText Property

Aspose.Words

DrawingML.AlternativeText Property

Gets or sets the alternative text (description) to be rendered when the graphics object cannot be rendered.

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

Remarks

The default value is an empty string.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


BehindText Property

Aspose.Words

DrawingML.BehindText Property

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

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


BoundsWithEffects Property

Aspose.Words

DrawingML.BoundsWithEffects Property

Gets final extent that DrawingML object has after applying drawing effects. Value is measured in points.

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

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


CanHaveImage Property

Aspose.Words

DrawingML.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;}

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


HasImage Property

Aspose.Words

DrawingML.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;}

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


Height Property

Aspose.Words

DrawingML.Height Property

Gets or sets the height of the shape in points.

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

Remarks

The default value is 0.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


HRef Property

Aspose.Words

DrawingML.HRef Property

Gets or sets the full hyperlink address for a DrawingML.

[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: http://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: http://www.aspose.com/Products/Default.aspx#Suites

Bookmark within this document: #BookmakName.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


ImageData Property

Aspose.Words

DrawingML.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 DrawingMLImageData
[C#]
public DrawingMLImageData ImageData {get;}

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


IsInline Property

Aspose.Words

DrawingML.IsInline Property

A quick way to determine if this DrawingML object 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 DrawingML objects.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


Name Property

Aspose.Words

DrawingML.Name Property

Gets or sets the optional DrawingML 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.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


NodeType Property

Aspose.Words

DrawingML.NodeType Property

Returns NodeType.DrawingML.

[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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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

DrawingML Class | Aspose.Words.Drawing Namespace


ScreenTip Property

Aspose.Words

DrawingML.ScreenTip Property

Defines the text displayed when the mouse pointer moves over the DrawingML.

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

Remarks

The default value is an empty string.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


Size Property

Aspose.Words

DrawingML.Size Property

Gets or sets the size of the shape in points.

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

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


Target Property

Aspose.Words

DrawingML.Target Property

Gets or sets the target frame for the DrawingML hyperlink.

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

Remarks

The default value is an empty string.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


Width Property

Aspose.Words

DrawingML.Width Property

Gets or sets the width of the shape in points.

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

Remarks

The default value is 0.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


ZOrder Property

Aspose.Words

DrawingML.ZOrder Property

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

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML Methods

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

Public Instance Methods

Accept | Accepts a visitor.
Clone (inherited from Node) | Creates a duplicate of the node.
FetchInheritedShapeAttr | Reserved for system use. IShapeAttrSource.
FetchShapeAttr | Reserved for system use. IShapeAttrSource.
GetAncestor (inherited from Node) | Overloaded. Gets the first ancestor of the specified object type.
GetDirectShapeAttr | Reserved for system use. IShapeAttrSource.
GetShapeRenderer | Creates and returns an object that can be used to render this shape into an image.
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.
RemoveShapeAttr | Reserved for system use. IShapeAttrSource.
SetShapeAttr | Reserved for system use. IShapeAttrSource.
ToString (inherited from Node) | Overloaded. Exports the content of the node into a string in the specified format.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML.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 VisitDrawingML.

For more info see the Visitor design pattern.

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML.FetchInheritedShapeAttr Method

Reserved for system use. IShapeAttrSource.

[Visual Basic]
NotOverridable Public Function FetchInheritedShapeAttr( _
ByVal key As Integer _
) As Object
[C#]
public object FetchInheritedShapeAttr(
int key
);

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML.FetchShapeAttr Method

Reserved for system use. IShapeAttrSource.

[Visual Basic]
NotOverridable Public Function FetchShapeAttr( _
ByVal key As Integer _
) As Object
[C#]
public object FetchShapeAttr(
int key
);

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML.GetDirectShapeAttr Method

Reserved for system use. IShapeAttrSource.

[Visual Basic]
NotOverridable Public Function GetDirectShapeAttr( _
ByVal key As Integer _
) As Object
[C#]
public object GetDirectShapeAttr(
int key
);

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML.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 render a DrawingML image independent of the document to a JPEG image on the disk.

[C#]

// Save the DrawingML image to disk in JPEG format and using default options.
drawingML.GetShapeRenderer().Save(dataDir + "TestFile.RenderDrawingML Out.jpg", null);
[Visual Basic]

' Save the DrawingML image to disk in JPEG format and using default options.
drawingML.GetShapeRenderer().Save(dataDir & "TestFile.RenderDrawingML Out.jpg", Nothing)

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML.RemoveShapeAttr Method

Reserved for system use. IShapeAttrSource.

[Visual Basic]
NotOverridable Public Sub RemoveShapeAttr( _
ByVal key As Integer _
)
[C#]
public void RemoveShapeAttr(
int key
);

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingML.SetShapeAttr Method

Reserved for system use. IShapeAttrSource.

[Visual Basic]
NotOverridable Public Sub SetShapeAttr( _
ByVal key As Integer, _
ByVal value As Object _
)
[C#]
public void SetShapeAttr(
int key,
object value
);

See Also

DrawingML Class | Aspose.Words.Drawing Namespace


DrawingMLImageData Class

Defines an image for a DrawingML picture.

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

System.Object
Aspose.Words.Drawing.DrawingMLImageData

[Visual Basic]
Public Class DrawingMLImageData
Implements IImageData
[C#]
public class DrawingMLImageData : IImageData

Remarks

Use the ImageData property to access and modify the image inside a DrawingML picture. You do not create instances of the DrawingMLImageData 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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

Requirements

Namespace: Aspose.Words.Drawing

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

See Also

DrawingMLImageData Members | Aspose.Words.Drawing Namespace


DrawingMLImageData Members

DrawingMLImageData overview

Public Instance Properties

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 DrawingML picture (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.

Public Instance Methods

Save | Overloaded. Saves the image of the DrawingML picture.
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 DrawingML picture as a .NET Image object.
ToStream | Creates and returns a stream that contains the image bytes.

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


DrawingMLImageData Properties

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

Public Instance Properties

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 DrawingML picture (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.

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


HasImage Property

Aspose.Words

DrawingMLImageData.HasImage Property

Returns true if the shape has image bytes or links an image.

[Visual Basic]
NotOverridable Public ReadOnly Property HasImage As Boolean _
Implements IImageData.HasImage
[C#]
public bool HasImage {get;}

Property Value

Implements

IImageData.HasImage

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


ImageBytes Property

Aspose.Words

DrawingMLImageData.ImageBytes Property

Gets or sets the raw bytes of the image stored in the shape.

[Visual Basic]
NotOverridable Public Property ImageBytes As Byte() _
Implements IImageData.ImageBytes
[C#]
public byte[] ImageBytes {get; set;}

Implements

IImageData.ImageBytes

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).

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace | SetImage | ToByteArray | ToImage | ToStream | Save


ImageSize Property

Aspose.Words

DrawingMLImageData.ImageSize Property

Gets the information about image size and resolution.

[Visual Basic]
NotOverridable Public ReadOnly Property ImageSize As ImageSize _
Implements IImageData.ImageSize
[C#]
public ImageSize ImageSize {get;}

Property Value

Implements

IImageData.ImageSize

Remarks

If the image is linked only and not stored in the document, returns zero size.

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


ImageType Property

Aspose.Words

DrawingMLImageData.ImageType Property

Gets the type of the image.

[Visual Basic]
NotOverridable Public ReadOnly Property ImageType As ImageType _
Implements IImageData.ImageType
[C#]
public ImageType ImageType {get;}

Property Value

Implements

IImageData.ImageType

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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


IsLink Property

Aspose.Words

DrawingMLImageData.IsLink Property

Returns true if the image is linked to the DrawingML picture (when SourceFullName is specified).

[Visual Basic]
NotOverridable Public ReadOnly Property IsLink As Boolean _
Implements IImageData.IsLink
[C#]
public bool IsLink {get;}

Property Value

Implements

IImageData.IsLink

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


IsLinkOnly Property

Aspose.Words

DrawingMLImageData.IsLinkOnly Property

Returns true if the image is linked and not stored in the document.

[Visual Basic]
NotOverridable Public ReadOnly Property IsLinkOnly As Boolean _
Implements IImageData.IsLinkOnly
[C#]
public bool IsLinkOnly {get;}

Property Value

Implements

IImageData.IsLinkOnly

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


SourceFullName Property

Aspose.Words

DrawingMLImageData.SourceFullName Property

Gets or sets the path and name of the source file for the linked image.

[Visual Basic]
NotOverridable Public Property SourceFullName As String _
Implements IImageData.SourceFullName
[C#]
public string SourceFullName {get; set;}

Implements

IImageData.SourceFullName

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


DrawingMLImageData Methods

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

Public Instance Methods

Save | Overloaded. Saves the image of the DrawingML picture.
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 DrawingML picture as a .NET Image object.
ToStream | Creates and returns a stream that contains the image bytes.

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


Save Method

Aspose.Words

DrawingMLImageData.Save Method

Saves the image of the DrawingML picture.

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

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


DrawingMLImageData.Save Method (Stream)

Saves the image into the specified stream.

[Visual Basic]
NotOverridable Overloads Public Sub Save( _
ByVal stream As Stream _
) _
Implements IImageData.Save
[C#]
public void Save(
Stream stream
);

Parameters

stream
The stream where to save the image to.

Implements

IImageData.Save

Remarks

Is it the responsibility of the caller to dispose the stream object.

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace | DrawingMLImageData.Save Overload List


DrawingMLImageData.Save Method (String)

Saves the image into a file.

[Visual Basic]
NotOverridable Overloads Public Sub Save( _
ByVal fileName As String _
) _
Implements IImageData.Save
[C#]
public void Save(
string fileName
);

Parameters

fileName
The file name where to save the image.

Implements

IImageData.Save

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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace | DrawingMLImageData.Save Overload List


SetImage Method

Aspose.Words

DrawingMLImageData.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 DrawingML picture displays.

public void SetImage(Stream);

Sets the image that the DrawingML picture displays.

public void SetImage(string);

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


DrawingMLImageData.SetImage Method (Image)

Sets the image that the shape displays.

[Visual Basic]
NotOverridable Overloads Public Sub SetImage( _
ByVal image As Image _
) _
Implements IImageData.SetImage
[C#]
public void SetImage(
Image image
);

Parameters

image
The image object.

Implements

IImageData.SetImage

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace | DrawingMLImageData.SetImage Overload List


DrawingMLImageData.SetImage Method (Stream)

Sets the image that the DrawingML picture displays.

[Visual Basic]
NotOverridable Overloads Public Sub SetImage( _
ByVal stream As Stream _
) _
Implements IImageData.SetImage
[C#]
public void SetImage(
Stream stream
);

Parameters

stream
The stream that contains the image.

Implements

IImageData.SetImage

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace | DrawingMLImageData.SetImage Overload List


DrawingMLImageData.SetImage Method (String)

Sets the image that the DrawingML picture displays.

[Visual Basic]
NotOverridable Overloads Public Sub SetImage( _
ByVal fileName As String _
) _
Implements IImageData.SetImage
[C#]
public void SetImage(
string fileName
);

Parameters

fileName
The image file. Can be a file name or a URL.

Implements

IImageData.SetImage

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace | DrawingMLImageData.SetImage Overload List


DrawingMLImageData.ToByteArray Method

Returns image bytes for any image regardless whether the image is stored or linked.

[Visual Basic]
NotOverridable Public Function ToByteArray() As Byte() _
Implements IImageData.ToByteArray
[C#]
public byte[] ToByteArray();

Return Value

Implements

IImageData.ToByteArray

Remarks

If the image is linked, downloads the image every time it is called.

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace | ImageBytes


DrawingMLImageData.ToImage Method

Gets the image stored in the DrawingML picture as a .NET Image object.

[Visual Basic]
NotOverridable Public Function ToImage() As Image _
Implements IImageData.ToImage
[C#]
public Image ToImage();

Return Value

Implements

IImageData.ToImage

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.

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


DrawingMLImageData.ToStream Method

Creates and returns a stream that contains the image bytes.

[Visual Basic]
NotOverridable Public Function ToStream() As Stream _
Implements IImageData.ToStream
[C#]
public Stream ToStream();

Implements

IImageData.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.

See Also

DrawingMLImageData Class | Aspose.Words.Drawing Namespace


EndCap Enumeration

Specifies line cap style.

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

Remarks

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(MyDir + "Shape.Fill Out.doc");
[Visual Basic]

Dim builder As 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.
Dim shape As 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(MyDir & "Shape.Fill Out.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.

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.

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.

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(MyDir + "Shape.Fill Out.doc");
[Visual Basic]

Dim builder As 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.
Dim shape As 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(MyDir & "Shape.Fill Out.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

Creates two line shapes. One line goes from top left to bottom right. Another line goes from bottom left to top right.

[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);
lineA.Bounds = new RectangleF(0, 0, pageWidth, pageHeight);
lineA.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
lineA.RelativeVerticalPosition = RelativeVerticalPosition.Page;
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA);

// This line goes from bottom left to top right because we flipped it.
Shape lineB = new Shape(doc, ShapeType.Line);
lineB.Bounds = new RectangleF(0, 0, pageWidth, pageHeight);
lineB.FlipOrientation = FlipOrientation.Horizontal;
lineB.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
lineB.RelativeVerticalPosition = RelativeVerticalPosition.Page;
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB);

doc.Save(MyDir + "Shape.LineFlipOrientation Out.doc");
[Visual Basic]

Dim doc As New Document()

' The lines will cross the whole page.
Dim pageWidth As Single = CSng(doc.FirstSection.PageSetup.PageWidth)
Dim pageHeight As Single= CSng(doc.FirstSection.PageSetup.PageHeight)

' This line goes from top left to bottom right by default.
Dim lineA As New Shape(doc, ShapeType.Line)
lineA.Bounds = New RectangleF(0, 0, pageWidth, pageHeight)
lineA.RelativeHorizontalPosition = RelativeHorizontalPosition.Page
lineA.RelativeVerticalPosition = RelativeVerticalPosition.Page
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA)

' This line goes from bottom left to top right because we flipped it.
Dim lineB As New Shape(doc, ShapeType.Line)
lineB.Bounds = New RectangleF(0, 0, pageWidth, pageHeight)
lineB.FlipOrientation = FlipOrientation.Horizontal
lineB.RelativeHorizontalPosition = RelativeHorizontalPosition.Page
lineB.RelativeVerticalPosition = RelativeVerticalPosition.Page
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB)

doc.Save(MyDir & "Shape.LineFlipOrientation Out.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.

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.
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.
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.
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.
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.
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.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

GroupShape Class | Aspose.Words.Drawing Namespace | ShapeBase | Shape


GroupShape Constructor

Creates a new group shape.

[Visual Basic]
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.

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.
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.
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.
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.
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.
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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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


IImageData Interface

Provides a common interface for manipulating images stored in VML-based and DrawingML-based shapes in a document.

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

[Visual Basic]
Public Interface IImageData
[C#]
public interface IImageData

Types that implement IImageData

Type | Description
DrawingMLImageData | Defines an image for a DrawingML picture.
ImageData | Defines an image for a VML-based shape.

Remarks

You can use this interface if you want to process images stored in a document (e.g. extract or replace) and you want to do that using the same code both for images stored in "old" VML-based and "new" DrawingML-based shapes.

Documents created by Microsoft Word 2003 or earlier had one type of graphical objects. These objects were VML (Vector Markup Language) based. In the Aspose.Words document model such objects are represented by the Shape and GroupShape classes. These shapes can be images or can contain images. You can access these images via the ImageData property that returns an object of the ImageData class.

Documents created by Microsoft Word 2007 or newer can have two types of graphical objects. The old VML-based shapes and also the new DrawingML-based shapes. DrawingML is part of the Office Open XML standard. In the Aspose.Words document model the new DrawingML-based shapes are represented by the DrawingML class. DrawingML shapes can also contain images. You can access these images via the ImageData property that returns an object of the DrawingMLImageData class.

The Shape and DrawingML classes are different because the underlying document elements are different. As a result, the two classes have two different mechanisms to access their respective image data using the ImageData and DrawingMLImageData classes. But there is some similarity between the two when it comes to operations with images and these operations are extracted into this IImageData interface for your convenience.

Requirements

Namespace: Aspose.Words.Drawing

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

See Also

IImageData Members | Aspose.Words.Drawing Namespace


IImageData Members

IImageData overview

Public Instance Properties

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.

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 .NET Image object.
ToStream | Creates and returns a stream that contains the image bytes.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


IImageData Properties

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

Public Instance Properties

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.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


HasImage Property

Aspose.Words

IImageData.HasImage Property

Returns true if the shape has image bytes or links an image.

[Visual Basic]
Property HasImage As Boolean
[C#]
bool HasImage {get;}

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


ImageBytes Property

Aspose.Words

IImageData.ImageBytes Property

Gets or sets the raw bytes of the image stored in the shape.

[Visual Basic]
Property ImageBytes As Byte()
[C#]
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).

See Also

IImageData Interface | Aspose.Words.Drawing Namespace | SetImage | ToByteArray | ToImage | ToStream | Save


ImageSize Property

Aspose.Words

IImageData.ImageSize Property

Gets the information about image size and resolution.

[Visual Basic]
Property ImageSize As ImageSize
[C#]
ImageSize ImageSize {get;}

Remarks

If the image is linked only and not stored in the document, returns zero size.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


ImageType Property

Aspose.Words

IImageData.ImageType Property

Gets the type of the image.

[Visual Basic]
Property ImageType As ImageType
[C#]
ImageType ImageType {get;}

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


IsLink Property

Aspose.Words

IImageData.IsLink Property

Returns true if the image is linked to the shape (when SourceFullName is specified).

[Visual Basic]
Property IsLink As Boolean
[C#]
bool IsLink {get;}

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


IsLinkOnly Property

Aspose.Words

IImageData.IsLinkOnly Property

Returns true if the image is linked and not stored in the document.

[Visual Basic]
Property IsLinkOnly As Boolean
[C#]
bool IsLinkOnly {get;}

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


SourceFullName Property

Aspose.Words

IImageData.SourceFullName Property

Gets or sets the path and name of the source file for the linked image.

[Visual Basic]
Property SourceFullName As String
[C#]
string SourceFullName {get; set;}

Remarks

The default value is an empty string.

If SourceFullName is not an empty string, the image is linked.

If SourceFullName is not an empty string, but ImageBytes is null, then the image is linked and not stored in the document.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


IImageData Methods

The methods of the IImageData interface are listed below. For a complete list of IImageData interface members, see the IImageData 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 .NET Image object.
ToStream | Creates and returns a stream that contains the image bytes.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


Save Method

Aspose.Words

IImageData.Save Method

Saves the image of the shape.

Overload List

Saves the image into the specified stream.

void Save(Stream);

Saves the image into a file.

void Save(string);

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


IImageData.Save Method (Stream)

Saves the image into the specified stream.

[Visual Basic]
Sub Save( _
ByVal stream As Stream _
)
[C#]
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.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace | IImageData.Save Overload List


IImageData.Save Method (String)

Saves the image into a file.

[Visual Basic]
Sub Save( _
ByVal fileName As String _
)
[C#]
void Save(
string fileName
);

Parameters

fileName
The file name where to save the image.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace | IImageData.Save Overload List


SetImage Method

Aspose.Words

IImageData.SetImage Method

Sets the image that the shape displays.

Overload List

Sets the image that the shape displays.

void SetImage(Image);

Sets the image that the shape displays.

void SetImage(Stream);

Sets the image that the shape displays.

void SetImage(string);

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


IImageData.SetImage Method (Image)

Sets the image that the shape displays.

[Visual Basic]
Sub SetImage( _
ByVal image As Image _
)
[C#]
void SetImage(
Image image
);

Parameters

image
The image object.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace | IImageData.SetImage Overload List


IImageData.SetImage Method (Stream)

Sets the image that the shape displays.

[Visual Basic]
Sub SetImage( _
ByVal stream As Stream _
)
[C#]
void SetImage(
Stream stream
);

Parameters

stream
The stream that contains the image.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace | IImageData.SetImage Overload List


IImageData.SetImage Method (String)

Sets the image that the shape displays.

[Visual Basic]
Sub SetImage( _
ByVal fileName As String _
)
[C#]
void SetImage(
string fileName
);

Parameters

fileName
The image file. Can be a file name or a URL.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace | IImageData.SetImage Overload List


IImageData.ToByteArray Method

Returns image bytes for any image regardless whether the image is stored or linked.

[Visual Basic]
Function ToByteArray() As Byte()
[C#]
byte[] ToByteArray();

Remarks

If the image is linked, downloads the image every time it is called.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace | ImageBytes


IImageData.ToImage Method

Gets the image stored in the shape as a .NET Image object.

[Visual Basic]
Function ToImage() As Image
[C#]
Image ToImage();

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.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


IImageData.ToStream Method

Creates and returns a stream that contains the image bytes.

[Visual Basic]
Function ToStream() As Stream
[C#]
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.

See Also

IImageData Interface | Aspose.Words.Drawing Namespace


ImageData Class

Defines an image for a VML-based shape.

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

System.Object
Aspose.Words.Drawing.ImageData

[Visual Basic]
Public Class ImageData
Implements IImageData
[C#]
public class ImageData : IImageData

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 insert a linked image into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "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(MyDir + "Image.CreateLinkedImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim imageFileName As String = MyDir & "Hammer.wmf"

builder.Write("Image linked, not stored in the document: ")

Dim linkedOnly As 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: ")

Dim linkedAndStored As 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: ")

Dim stored As New Shape(builder.Document, ShapeType.Image)
stored.WrapType = WrapType.Inline
stored.ImageData.SetImage(imageFileName)

builder.InsertNode(stored)
builder.Writeln()

builder.Document.Save(MyDir & "Image.CreateLinkedImage Out.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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

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 .NET 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.

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;}

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.

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.

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.

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.

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.

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.

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.

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.

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]
NotOverridable Public ReadOnly Property HasImage As Boolean _
Implements IImageData.HasImage
[C#]
public bool HasImage {get;}

Property Value

Implements

IImageData.HasImage

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]
NotOverridable Public Property ImageBytes As Byte() _
Implements IImageData.ImageBytes
[C#]
public byte[] ImageBytes {get; set;}

Implements

IImageData.ImageBytes

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).

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]
NotOverridable Public ReadOnly Property ImageSize As ImageSize _
Implements IImageData.ImageSize
[C#]
public ImageSize ImageSize {get;}

Property Value

Implements

IImageData.ImageSize

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 + "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(MyDir + "Image.ScaleImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

' By default, the image is inserted at 100% scale.
Dim shape As Shape = builder.InsertImage(MyDir & "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%.
Dim imageSize As ImageSize = shape.ImageData.ImageSize
shape.Width = imageSize.WidthPoints * 1.1
shape.Height = imageSize.HeightPoints * 1.1

builder.Document.Save(MyDir & "Image.ScaleImage Out.doc")

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageType Property

Aspose.Words

ImageData.ImageType Property

Gets the type of the image.

[Visual Basic]
NotOverridable Public ReadOnly Property ImageType As ImageType _
Implements IImageData.ImageType
[C#]
public ImageType ImageType {get;}

Property Value

Implements

IImageData.ImageType

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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

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]
NotOverridable Public ReadOnly Property IsLink As Boolean _
Implements IImageData.IsLink
[C#]
public bool IsLink {get;}

Property Value

Implements

IImageData.IsLink

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]
NotOverridable Public ReadOnly Property IsLinkOnly As Boolean _
Implements IImageData.IsLinkOnly
[C#]
public bool IsLinkOnly {get;}

Property Value

Implements

IImageData.IsLinkOnly

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]
NotOverridable Public Property SourceFullName As String _
Implements IImageData.SourceFullName
[C#]
public string SourceFullName {get; set;}

Implements

IImageData.SourceFullName

Example

Shows how to insert a linked image into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "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(MyDir + "Image.CreateLinkedImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim imageFileName As String = MyDir & "Hammer.wmf"

builder.Write("Image linked, not stored in the document: ")

Dim linkedOnly As 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: ")

Dim linkedAndStored As 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: ")

Dim stored As New Shape(builder.Document, ShapeType.Image)
stored.WrapType = WrapType.Inline
stored.ImageData.SetImage(imageFileName)

builder.InsertNode(stored)
builder.Writeln()

builder.Document.Save(MyDir & "Image.CreateLinkedImage Out.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.

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 .NET 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]
NotOverridable Overloads Public Sub Save( _
ByVal stream As Stream _
) _
Implements IImageData.Save
[C#]
public void Save(
Stream stream
);

Parameters

stream
The stream where to save the image to.

Implements

IImageData.Save

Remarks

Is it the responsibility of the caller to dispose the stream object.

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageData.Save Overload List


ImageData.Save Method (String)

Saves the image into a file.

[Visual Basic]
NotOverridable Overloads Public Sub Save( _
ByVal fileName As String _
) _
Implements IImageData.Save
[C#]
public void Save(
string fileName
);

Parameters

fileName
The file name where to save the image.

Implements

IImageData.Save

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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageData.Save Overload List


SetImage Method

Aspose.Words

ImageData.SetImage Method

NOTE: This method is now obsolete.

Please use the ImageBytes property to set an image.

Sets the image that the shape displays.

Overload List

Obsolete. Sets the image that the shape displays.

public void SetImage(byte[]);

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 (Byte[])

NOTE: This method is now obsolete.

Please use the ImageBytes property to set an image.

Sets the image that the shape displays.

[Visual Basic]
Overloads Public Sub SetImage( _
ByVal imageBytes As Byte() _
)
[C#]
public void SetImage(
byte[] imageBytes
);

Parameters

imageBytes
Bytes of the image.

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageData.SetImage Overload List


ImageData.SetImage Method (Image)

Sets the image that the shape displays.

[Visual Basic]
NotOverridable Overloads Public Sub SetImage( _
ByVal image As Image _
) _
Implements IImageData.SetImage
[C#]
public void SetImage(
Image image
);

Parameters

image
The image object.

Implements

IImageData.SetImage

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]
NotOverridable Overloads Public Sub SetImage( _
ByVal stream As Stream _
) _
Implements IImageData.SetImage
[C#]
public void SetImage(
Stream stream
);

Parameters

stream
The stream that contains the image.

Implements

IImageData.SetImage

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]
NotOverridable Overloads Public Sub SetImage( _
ByVal fileName As String _
) _
Implements IImageData.SetImage
[C#]
public void SetImage(
string fileName
);

Parameters

fileName
The image file. Can be a file name or a URL.

Implements

IImageData.SetImage

Example

Shows how to insert a linked image into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "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(MyDir + "Image.CreateLinkedImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim imageFileName As String = MyDir & "Hammer.wmf"

builder.Write("Image linked, not stored in the document: ")

Dim linkedOnly As 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: ")

Dim linkedAndStored As 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: ")

Dim stored As New Shape(builder.Document, ShapeType.Image)
stored.WrapType = WrapType.Inline
stored.ImageData.SetImage(imageFileName)

builder.InsertNode(stored)
builder.Writeln()

builder.Document.Save(MyDir & "Image.CreateLinkedImage Out.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]
NotOverridable Public Function ToByteArray() As Byte() _
Implements IImageData.ToByteArray
[C#]
public byte[] ToByteArray();

Return Value

Implements

IImageData.ToByteArray

Remarks

If the image is linked, downloads the image every time it is called.

See Also

ImageData Class | Aspose.Words.Drawing Namespace | ImageBytes


ImageData.ToImage Method

Gets the image stored in the shape as a .NET Image object.

[Visual Basic]
NotOverridable Public Function ToImage() As Image _
Implements IImageData.ToImage
[C#]
public Image ToImage();

Return Value

Implements

IImageData.ToImage

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.

See Also

ImageData Class | Aspose.Words.Drawing Namespace


ImageData.ToStream Method

Creates and returns a stream that contains the image bytes.

[Visual Basic]
NotOverridable Public Function ToStream() As Stream _
Implements IImageData.ToStream
[C#]
public Stream ToStream();

Implements

IImageData.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.

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 + "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(MyDir + "Image.ScaleImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

' By default, the image is inserted at 100% scale.
Dim shape As Shape = builder.InsertImage(MyDir & "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%.
Dim imageSize As ImageSize = shape.ImageData.ImageSize
shape.Width = imageSize.WidthPoints * 1.1
shape.Height = imageSize.HeightPoints * 1.1

builder.Document.Save(MyDir & "Image.ScaleImage Out.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;}

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 + "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(MyDir + "Image.ScaleImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

' By default, the image is inserted at 100% scale.
Dim shape As Shape = builder.InsertImage(MyDir & "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%.
Dim imageSize As ImageSize = shape.ImageData.ImageSize
shape.Width = imageSize.WidthPoints * 1.1
shape.Height = imageSize.HeightPoints * 1.1

builder.Document.Save(MyDir & "Image.ScaleImage Out.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;}

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;}

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;}

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 + "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(MyDir + "Image.ScaleImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

' By default, the image is inserted at 100% scale.
Dim shape As Shape = builder.InsertImage(MyDir & "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%.
Dim imageSize As ImageSize = shape.ImageData.ImageSize
shape.Width = imageSize.WidthPoints * 1.1
shape.Height = imageSize.HeightPoints * 1.1

builder.Document.Save(MyDir & "Image.ScaleImage Out.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

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

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

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.

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.
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.
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.

Public Instance Methods

GetOleEntry | Gets a named stream from OLE object data.
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.
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.
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.

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.

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;}

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;}

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;}

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.

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.

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.

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.

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.

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;}

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 a named stream from OLE object data.
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 a named stream from OLE object data.

[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.

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.

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.

See Also

OleFormat Class | Aspose.Words.Drawing Namespace | OleFormat.Save Overload List


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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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(MyDir + "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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(MyDir + "DocumentBuilder.InsertWatermark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)

Dim image As Image = Image.FromFile(MyDir & "Watermark.png")

' Insert a floating picture.
Dim shape As 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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2

doc.Save(MyDir & "DocumentBuilder.InsertWatermark Out.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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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(MyDir + "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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(MyDir + "DocumentBuilder.InsertWatermark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)

Dim image As Image = Image.FromFile(MyDir & "Watermark.png")

' Insert a floating picture.
Dim shape As 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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2

doc.Save(MyDir & "DocumentBuilder.InsertWatermark Out.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]
Public Class Shape
Inherits ShapeBase
[C#]
public 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();
[Visual Basic]

' 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.
Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
shapes.Clear()

' There could also be group shapes, they have different node type, remove them all too.
Dim groupShapes As NodeCollection = doc.GetChildNodes(NodeType.GroupShape, True)
groupShapes.Clear()
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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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 + "Hammer.wmf");
shape.Width = 100;
shape.Height = 100;

doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

doc.Save(MyDir + "Image.CreateImageDirectly Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim shape As New Shape(doc, ShapeType.Image)
shape.ImageData.SetImage(MyDir & "Hammer.wmf")
shape.Width = 100
shape.Height = 100

doc.FirstSection.Body.FirstParagraph.AppendChild(shape)

doc.Save(MyDir & "Image.CreateImageDirectly Out.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(MyDir + "Shape.CreateTextBox Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()

' Create a new shape of type TextBox
Dim textBox As 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))
Dim para As Paragraph = textBox.FirstParagraph
para.ParagraphFormat.Alignment = ParagraphAlignment.Center

' Add some text to the paragraph.
Dim run As 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(MyDir & "Shape.CreateTextBox Out.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.
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.
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.
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.
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.
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.
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.
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.
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).
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


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;}

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(MyDir + "Shape.Fill Out.doc");
[Visual Basic]

Dim builder As 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.
Dim shape As 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(MyDir & "Shape.Fill Out.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(MyDir + "Shape.Fill Out.doc");
[Visual Basic]

Dim builder As 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.
Dim shape As 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(MyDir & "Shape.Fill Out.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.

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(MyDir + "Shape.CreateTextBox Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()

' Create a new shape of type TextBox
Dim textBox As 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))
Dim para As Paragraph = textBox.FirstParagraph
para.ParagraphFormat.Alignment = ParagraphAlignment.Center

' Add some text to the paragraph.
Dim run As 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(MyDir & "Shape.CreateTextBox Out.doc")

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 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)
{
    // 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();
[Visual Basic]

' 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.
Dim shapes As NodeCollection = 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.
Dim shapesToDelete As New ArrayList()
For Each shape As Shape In shapes
    ' Several shape types can have an image including image shapes and OLE objects.
    If shape.HasImage Then
        shapesToDelete.Add(shape)
    End If
Next shape

' Now we can delete shapes.
For Each shape As Shape In shapesToDelete
    shape.Remove()
Next shape
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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

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 insert a linked image into a document.

[C#]

DocumentBuilder builder = new DocumentBuilder();

string imageFileName = MyDir + "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(MyDir + "Image.CreateLinkedImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

Dim imageFileName As String = MyDir & "Hammer.wmf"

builder.Write("Image linked, not stored in the document: ")

Dim linkedOnly As 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: ")

Dim linkedAndStored As 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: ")

Dim stored As New Shape(builder.Document, ShapeType.Image)
stored.WrapType = WrapType.Inline
stored.ImageData.SetImage(imageFileName)

builder.InsertNode(stored)
builder.Writeln()

builder.Document.Save(MyDir & "Image.CreateLinkedImage Out.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)
    {
        if (shape.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
            shape.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }

    // Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    // Repeat the process to extract these if they are present in the loaded document.
    NodeCollection dmlShapes = doc.GetChildNodes(NodeType.DrawingML, true);
    foreach (DrawingML dml in dmlShapes)
    {
        if (dml.HasImage)
        {
            string imageFileName = string.Format(
                "Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType));
            dml.ImageData.Save(MyDir + imageFileName);
            imageIndex++;
        }
    }
}
[Visual Basic]

<Test> _
Public Sub ExtractImagesToFiles()
    Dim doc As New Document(MyDir & "Image.SampleImages.doc")

    Dim shapes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)
    Dim imageIndex As Integer = 0
    For Each shape As Shape In shapes
        If shape.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType))
            shape.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next shape

    ' Newer Microsoft Word documents (such as DOCX) may contain a different type of image container called DrawingML.
    ' Repeat the process to extract these if they are present in the loaded document.
    Dim dmlShapes As NodeCollection = doc.GetChildNodes(NodeType.DrawingML, True)
    For Each dml As DrawingML In dmlShapes
        If dml.HasImage Then
            Dim imageFileName As String = String.Format("Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(dml.ImageData.ImageType))
            dml.ImageData.Save(MyDir & imageFileName)
            imageIndex += 1
        End If
    Next dml
End Sub

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 render a paragraph with a custom background color independent of the document.

[C#]

// Retrieve the first paragraph in the main shape.
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
Paragraph paragraph = (Paragraph)shape.LastParagraph;

// Save the node with a light pink background.
ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png);
options.PaperColor = Color.LightPink;

RenderNode(paragraph, dataDir + "TestFile.RenderParagraph Out.png", options);
[Visual Basic]

' Retrieve the first paragraph in the main shape.
Dim shape As Shape = CType(doc.GetChild(NodeType.Shape, 0, True), Shape)
Dim paragraph As Paragraph = CType(shape.LastParagraph, Paragraph)

' Save the node with a light pink background.
Dim options As New ImageSaveOptions(SaveFormat.Png)
options.PaperColor = Color.LightPink

RenderNode(paragraph, dataDir & "TestFile.RenderParagraph Out.png", options)

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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;}

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;}

See Also

Shape Class | Aspose.Words.Drawing Namespace


StoryType Property

Aspose.Words

Shape.StoryType Property

Returns Textbox.

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

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;}

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.

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.

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.

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;}

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;}

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.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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.
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.
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.
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.
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.
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.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
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.
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.
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.
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.
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.

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.

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.

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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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.

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

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

Creates two line shapes. One line goes from top left to bottom right. Another line goes from bottom left to top right.

[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);
lineA.Bounds = new RectangleF(0, 0, pageWidth, pageHeight);
lineA.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
lineA.RelativeVerticalPosition = RelativeVerticalPosition.Page;
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA);

// This line goes from bottom left to top right because we flipped it.
Shape lineB = new Shape(doc, ShapeType.Line);
lineB.Bounds = new RectangleF(0, 0, pageWidth, pageHeight);
lineB.FlipOrientation = FlipOrientation.Horizontal;
lineB.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
lineB.RelativeVerticalPosition = RelativeVerticalPosition.Page;
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB);

doc.Save(MyDir + "Shape.LineFlipOrientation Out.doc");
[Visual Basic]

Dim doc As New Document()

' The lines will cross the whole page.
Dim pageWidth As Single = CSng(doc.FirstSection.PageSetup.PageWidth)
Dim pageHeight As Single= CSng(doc.FirstSection.PageSetup.PageHeight)

' This line goes from top left to bottom right by default.
Dim lineA As New Shape(doc, ShapeType.Line)
lineA.Bounds = New RectangleF(0, 0, pageWidth, pageHeight)
lineA.RelativeHorizontalPosition = RelativeHorizontalPosition.Page
lineA.RelativeVerticalPosition = RelativeVerticalPosition.Page
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA)

' This line goes from bottom left to top right because we flipped it.
Dim lineB As New Shape(doc, ShapeType.Line)
lineB.Bounds = New RectangleF(0, 0, pageWidth, pageHeight)
lineB.FlipOrientation = FlipOrientation.Horizontal
lineB.RelativeHorizontalPosition = RelativeHorizontalPosition.Page
lineB.RelativeVerticalPosition = RelativeVerticalPosition.Page
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB)

doc.Save(MyDir & "Shape.LineFlipOrientation Out.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;}

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.

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).

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).

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.

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.

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.

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.

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

Creates two line shapes. One line goes from top left to bottom right. Another line goes from bottom left to top right.

[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);
lineA.Bounds = new RectangleF(0, 0, pageWidth, pageHeight);
lineA.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
lineA.RelativeVerticalPosition = RelativeVerticalPosition.Page;
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA);

// This line goes from bottom left to top right because we flipped it.
Shape lineB = new Shape(doc, ShapeType.Line);
lineB.Bounds = new RectangleF(0, 0, pageWidth, pageHeight);
lineB.FlipOrientation = FlipOrientation.Horizontal;
lineB.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
lineB.RelativeVerticalPosition = RelativeVerticalPosition.Page;
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB);

doc.Save(MyDir + "Shape.LineFlipOrientation Out.doc");
[Visual Basic]

Dim doc As New Document()

' The lines will cross the whole page.
Dim pageWidth As Single = CSng(doc.FirstSection.PageSetup.PageWidth)
Dim pageHeight As Single= CSng(doc.FirstSection.PageSetup.PageHeight)

' This line goes from top left to bottom right by default.
Dim lineA As New Shape(doc, ShapeType.Line)
lineA.Bounds = New RectangleF(0, 0, pageWidth, pageHeight)
lineA.RelativeHorizontalPosition = RelativeHorizontalPosition.Page
lineA.RelativeVerticalPosition = RelativeVerticalPosition.Page
doc.FirstSection.Body.FirstParagraph.AppendChild(lineA)

' This line goes from bottom left to top right because we flipped it.
Dim lineB As New Shape(doc, ShapeType.Line)
lineB.Bounds = New RectangleF(0, 0, pageWidth, pageHeight)
lineB.FlipOrientation = FlipOrientation.Horizontal
lineB.RelativeHorizontalPosition = RelativeHorizontalPosition.Page
lineB.RelativeVerticalPosition = RelativeVerticalPosition.Page
doc.FirstSection.Body.FirstParagraph.AppendChild(lineB)

doc.Save(MyDir & "Shape.LineFlipOrientation Out.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;}

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 + "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(MyDir + "Image.ScaleImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

' By default, the image is inserted at 100% scale.
Dim shape As Shape = builder.InsertImage(MyDir & "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%.
Dim imageSize As ImageSize = shape.ImageData.ImageSize
shape.Width = imageSize.WidthPoints * 1.1
shape.Height = imageSize.HeightPoints * 1.1

builder.Document.Save(MyDir & "Image.ScaleImage Out.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 + "Hammer.wmf");

// 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;

// Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0;
shape.Top = 0;
shape.Width = builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;

builder.Document.Save(MyDir + "Image.CreateFloatingPositionSize Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "Hammer.wmf")

' 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

' Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0
shape.Top = 0
shape.Width = builder.CurrentSection.PageSetup.PageWidth
shape.Height = 50

builder.Document.Save(MyDir & "Image.CreateFloatingPositionSize Out.doc")

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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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: http://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: http://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 + "Hammer.wmf");
shape.HRef = "http://www.aspose.com/Community/Forums/75/ShowForum.aspx";
shape.ScreenTip = "Aspose.Words Support Forums";

builder.Document.Save(MyDir + "Image.InsertImageWithHyperlink Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

Dim shape As Shape = builder.InsertImage(MyDir & "Hammer.wmf")
shape.HRef = "http://www.aspose.com/Community/Forums/75/ShowForum.aspx"
shape.ScreenTip = "Aspose.Words Support Forums"

builder.Document.Save(MyDir & "Image.InsertImageWithHyperlink Out.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;}

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;}

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;}

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;}

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))
{
    if(shape.IsInline)
        Console.WriteLine("Shape is inline.");
    else
        Console.WriteLine("Shape is floating.");
}
[Visual Basic]

Dim doc As New Document(MyDir & "Shape.DeleteAllShapes.doc")

For Each shape As Shape In doc.GetChildNodes(NodeType.Shape, True)
    If shape.IsInline Then
        Console.WriteLine("Shape is inline.")
    Else
        Console.WriteLine("Shape is floating.")
    End If
Next shape

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;}

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;}

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;}

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 + "Hammer.wmf");

// 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;

// Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0;
shape.Top = 0;
shape.Width = builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;

builder.Document.Save(MyDir + "Image.CreateFloatingPositionSize Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "Hammer.wmf")

' 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

' Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0
shape.Top = 0
shape.Width = builder.CurrentSection.PageSetup.PageWidth
shape.Height = 50

builder.Document.Save(MyDir & "Image.CreateFloatingPositionSize Out.doc")

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.

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 always returns null.

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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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.

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.

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 + "Hammer.wmf");
shape.HRef = "http://www.aspose.com/Community/Forums/75/ShowForum.aspx";
shape.ScreenTip = "Aspose.Words Support Forums";

builder.Document.Save(MyDir + "Image.InsertImageWithHyperlink Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

Dim shape As Shape = builder.InsertImage(MyDir & "Hammer.wmf")
shape.HRef = "http://www.aspose.com/Community/Forums/75/ShowForum.aspx"
shape.ScreenTip = "Aspose.Words Support Forums"

builder.Document.Save(MyDir & "Image.InsertImageWithHyperlink Out.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;}

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;}

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.

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 + "Hammer.wmf");

// 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;

// Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0;
shape.Top = 0;
shape.Width = builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;

builder.Document.Save(MyDir + "Image.CreateFloatingPositionSize Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "Hammer.wmf")

' 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

' Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0
shape.Top = 0
shape.Width = builder.CurrentSection.PageSetup.PageWidth
shape.Height = 50

builder.Document.Save(MyDir & "Image.CreateFloatingPositionSize Out.doc")

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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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 + "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(MyDir + "Image.ScaleImage Out.doc");
[Visual Basic]

Dim builder As New DocumentBuilder()

' By default, the image is inserted at 100% scale.
Dim shape As Shape = builder.InsertImage(MyDir & "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%.
Dim imageSize As ImageSize = shape.ImageData.ImageSize
shape.Width = imageSize.WidthPoints * 1.1
shape.Height = imageSize.HeightPoints * 1.1

builder.Document.Save(MyDir & "Image.ScaleImage Out.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 + "Hammer.wmf");

// 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;

// Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0;
shape.Top = 0;
shape.Width = builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;

builder.Document.Save(MyDir + "Image.CreateFloatingPositionSize Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "Hammer.wmf")

' 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

' Make the shape occupy a band 50 points high at the very top of the page.
shape.Left = 0
shape.Top = 0
shape.Width = builder.CurrentSection.PageSetup.PageWidth
shape.Height = 50

builder.Document.Save(MyDir & "Image.CreateFloatingPositionSize Out.doc")

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)
{
    // 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(MyDir + "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(MyDir + "Shape.ReplaceTextboxesWithImages Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Shape.ReplaceTextboxesWithImages.doc")

' This gets a live collection of all shape nodes in the document.
Dim shapeCollection As NodeCollection = 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.
Dim shapes() As Node = shapeCollection.ToArray()

For Each shape As Shape In shapes
    ' Filter out all shapes that we don't need.
    If shape.ShapeType.Equals(ShapeType.TextBox) Then
        ' Create a new shape that will replace the existing shape.
        Dim image As New Shape(doc, ShapeType.Image)

        ' Load the image into the new shape.
        image.ImageData.SetImage(MyDir & "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()
    End If
Next shape

doc.Save(MyDir & "Shape.ReplaceTextboxesWithImages Out.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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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(MyDir + "Shape.CreateTextBox Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()

' Create a new shape of type TextBox
Dim textBox As 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))
Dim para As Paragraph = textBox.FirstParagraph
para.ParagraphFormat.Alignment = ParagraphAlignment.Center

' Add some text to the paragraph.
Dim run As 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(MyDir & "Shape.CreateTextBox Out.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(MyDir + "Shape.CreateTextBox Out.doc");
[Visual Basic]

' Create a blank document.
Dim doc As New Document()

' Create a new shape of type TextBox
Dim textBox As 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))
Dim para As Paragraph = textBox.FirstParagraph
para.ParagraphFormat.Alignment = ParagraphAlignment.Center

' Add some text to the paragraph.
Dim run As 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(MyDir & "Shape.CreateTextBox Out.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.
AppendChild (inherited from CompositeNode) | Adds the specified node to the end of the list of child nodes for this node.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

ShapeBase Class | Aspose.Words.Drawing Namespace | Shape | GroupShape


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 render a shape independent of the document to an EMF image and save it to disk.

[C#]

// The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Emf)
{
    Scale = 1.5f
};

// Save the rendered image to disk.
r.Save(dataDir + "TestFile.RenderToDisk Out.emf", imageOptions);
[Visual Basic]

' The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Emf) With {.Scale = 1.5f}

' Save the rendered image to disk.
r.Save(dataDir & "TestFile.RenderToDisk Out.emf", imageOptions)
Shows how to render a shape independent of the document to a .NET Graphics object and apply rotation to the rendered image.
[C#]

// The shape renderer is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Find the size that the shape will be rendered to at the specified scale and resolution.
Size shapeSizeInPixels = r.GetSizeInPixels(1.0f, 96.0f);

// Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
// and make sure that the graphics canvas is large enough to compensate for this.
int maxSide = Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height);

using (Bitmap image = new Bitmap((int)(maxSide * 1.25), (int)(maxSide * 1.25)))
{
    // Rendering to a graphics object means we can specify settings and transformations to be applied to
    // the shape that is rendered. In our case we will rotate the rendered shape.
    using (Graphics gr = Graphics.FromImage(image))
    {
        // Clear the shape with the background color of the document.
        gr.Clear(Color.White);
        // Center the rotation using translation method below
        gr.TranslateTransform((float)image.Width / 8, (float)image.Height / 2);
        // Rotate the image by 45 degrees.
        gr.RotateTransform(45);
        // Undo the translation.
        gr.TranslateTransform(-(float)image.Width / 8, -(float)image.Height / 2);

        // Render the shape onto the graphics object.
        r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height);
    }

    image.Save(dataDir + "TestFile.RenderToGraphics.png", ImageFormat.Png);
}
[Visual Basic]

' The shape renderer is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Find the size that the shape will be rendered to at the specified scale and resolution.
Dim shapeSizeInPixels As Size = r.GetSizeInPixels(1.0f, 96.0f)

' Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
' and make sure that the graphics canvas is large enough to compensate for this.
Dim maxSide As Integer = Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height)

Using image As New Bitmap(CInt(Fix(maxSide * 1.25)), CInt(Fix(maxSide * 1.25)))
    ' Rendering to a graphics object means we can specify settings and transformations to be applied to
    ' the shape that is rendered. In our case we will rotate the rendered shape.
    Using gr As Graphics = Graphics.FromImage(image)
        ' Clear the shape with the background color of the document.
        gr.Clear(Color.White)
        ' Center the rotation using translation method below
        gr.TranslateTransform(CSng(image.Width) / 8, CSng(image.Height) / 2)
        ' Rotate the image by 45 degrees.
        gr.RotateTransform(45)
        ' Undo the translation.
        gr.TranslateTransform(-CSng(image.Width) / 8, -CSng(image.Height) / 2)

        ' Render the shape onto the graphics object.
        r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height)
    End Using

    image.Save(dataDir & "TestFile.RenderToGraphics.png", ImageFormat.Png)
End Using

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
);

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

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


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 + "Hammer.wmf");
shape.Width = 100;
shape.Height = 100;

doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

doc.Save(MyDir + "Image.CreateImageDirectly Out.doc");
[Visual Basic]

Dim doc As New Document()

Dim shape As New Shape(doc, ShapeType.Image)
shape.ImageData.SetImage(MyDir & "Hammer.wmf")
shape.Width = 100
shape.Height = 100

doc.FirstSection.Body.FirstParagraph.AppendChild(shape)

doc.Save(MyDir & "Image.CreateImageDirectly Out.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
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


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.

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.

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.

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.

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.

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.

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.

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.

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;}

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.
TextBoxWrapMode | Determines how text wraps inside a shape.

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.
TextBoxWrapMode | Determines how text wraps inside 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.

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.

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.

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.

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.

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.

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.

See Also

TextBox Class | Aspose.Words.Drawing Namespace


TextBoxWrapMode Enumeration

Specifies how text wraps inside a shape.

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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

See Also

TextPath Class | Aspose.Words.Drawing Namespace


TextPathAlignment Enumeration

WordArt alignment.

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

Remarks

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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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)
{
    // 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(MyDir + "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(MyDir + "Shape.ReplaceTextboxesWithImages Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Shape.ReplaceTextboxesWithImages.doc")

' This gets a live collection of all shape nodes in the document.
Dim shapeCollection As NodeCollection = 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.
Dim shapes() As Node = shapeCollection.ToArray()

For Each shape As Shape In shapes
    ' Filter out all shapes that we don't need.
    If shape.ShapeType.Equals(ShapeType.TextBox) Then
        ' Create a new shape that will replace the existing shape.
        Dim image As New Shape(doc, ShapeType.Image)

        ' Load the image into the new shape.
        image.ImageData.SetImage(MyDir & "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()
    End If
Next shape

doc.Save(MyDir & "Shape.ReplaceTextboxesWithImages Out.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 + "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(MyDir + "Image.CreateFloatingPageCenter Out.doc");
[Visual Basic]

' This creates a builder and also an empty document inside the builder.
Dim builder As New DocumentBuilder()

' By default, the image is inline.
Dim shape As Shape = builder.InsertImage(MyDir & "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(MyDir & "Image.CreateFloatingPageCenter Out.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(MyDir + "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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2;
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2;

doc.Save(MyDir + "DocumentBuilder.InsertWatermark Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)

Dim image As Image = Image.FromFile(MyDir & "Watermark.png")

' Insert a floating picture.
Dim shape As 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 centre of the page.
shape.Left = (builder.PageSetup.PageWidth - shape.Width) / 2
shape.Top = (builder.PageSetup.PageHeight - shape.Height) / 2

doc.Save(MyDir & "DocumentBuilder.InsertWatermark Out.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.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
DropDownItemCollection | A collection of strings that represent all the items in a drop-down form field.
Field | Represents a Microsoft Word document field.
FieldChar | Base class for nodes that represent field characters in a document.
FieldCollection | A collection of Field objects that represents the fields in the specified range.
FieldEnd | Represents an end of a Word field in a document.
FieldOptions | Represents options to control field handling in a document.
FieldSeparator | Represents a Word field separator that separates the field code from the field result.
FieldStart | Represents a start of a Word field in a document.
FormField | Represents a single form field.
FormFieldCollection | A collection of FormField objects that represent all the form fields in a range.
MergeFieldImageDimension | Represents an image dimension (i.e. the width or the height) used across a mail merge process.

Interfaces

Interface | Description
IFieldUserPromptRespondent | Represents the respondent to user prompts during field update.

Enumerations

Enumeration | Description
FieldType | Enumeration that identifies all different types of Word fields.
FieldUpdateCultureSource | Indicates what culture to use during field update.
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.


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
[C#]
public class DropDownItemCollection : IEnumerable

Remarks

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;}

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;}

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.

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();

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.

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

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.

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.

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.

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

[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.

[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 behaviour 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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.
Dim dateField As Field = 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 behaviour 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

End | Gets the node that represents the field end.
IsLocked | Gets or sets whether the field is locked (should not recalculate its result).
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 | Returns text between field start and field separator (or field end if there is no separator).
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.
Update | 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

End | Gets the node that represents the field end.
IsLocked | Gets or sets whether the field is locked (should not recalculate its result).
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


End Property

Aspose.Words

Field.End Property

Gets the node that represents the field end.

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

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;}

See Also

Field Class | Aspose.Words.Fields Namespace


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.

[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 behaviour 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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.
Dim dateField As Field = 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 behaviour 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]
Public ReadOnly Property Separator As FieldSeparator
[C#]
public FieldSeparator Separator {get;}

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]
Public ReadOnly Property Start As FieldStart
[C#]
public FieldStart Start {get;}

See Also

Field Class | Aspose.Words.Fields Namespace


Type Property

Aspose.Words

Field.Type Property

Gets the Microsoft Word field type.

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

Example

Inserts a field into a document using DocumentBuilder.

[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 behaviour 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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.
Dim dateField As Field = 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 behaviour 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 | Returns text between field start and field separator (or field end if there is no separator).
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.
Update | Performs the field update. Throws if the field is being updated already.

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).

[Visual Basic]
Public Function GetFieldCode() As String
[C#]
public string GetFieldCode();

Example

Inserts a field into a document using DocumentBuilder.

[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 behaviour 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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.
Dim dateField As Field = 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 behaviour 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.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.

[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 behaviour 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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.
Dim dateField As Field = 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 behaviour 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 Method

Performs the field update. Throws if the field is being updated already.

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

Example

Inserts a field into a document using DocumentBuilder.

[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 behaviour 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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.
Dim dateField As Field = 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 behaviour 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


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

Shows how to find the type of field that is represented by a node which is derived from FieldChar.

[C#]

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
FieldType type = fieldStart.FieldType;
[Visual Basic]

Dim fieldStart As FieldChar = CType(doc.GetChild(NodeType.FieldStart, 0, True), FieldChar)
Dim type As FieldType = fieldStart.FieldType

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.
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).
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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
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).
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

Shows how to find the type of field that is represented by a node which is derived from FieldChar.

[C#]

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
FieldType type = fieldStart.FieldType;
[Visual Basic]

Dim fieldStart As FieldChar = CType(doc.GetChild(NodeType.FieldStart, 0, True), FieldChar)
Dim type As FieldType = fieldStart.FieldType

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;}

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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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");

FieldStart fieldStart = (FieldStart)doc.GetChild(NodeType.FieldStart, 0, true);

// Retrieve the facade object which represents the field in the document.
Field field = fieldStart.GetField();

Console.WriteLine("Field code:" + field.GetFieldCode());
Console.WriteLine("Field result: " + field.Result);
Console.WriteLine("Is locked: " + field.IsLocked);

// This updates only this field in the document.
field.Update();
[Visual Basic]

Dim doc As New Document(MyDir & "Document.TableOfContents.doc")

Dim fieldStart As FieldStart = CType(doc.GetChild(NodeType.FieldStart, 0, True), FieldStart)

' Retrieve the facade object which represents the field in the document.
Dim field As Field = fieldStart.GetField()

Console.WriteLine("Field code:" & field.GetFieldCode())
Console.WriteLine("Field result: " & field.Result)
Console.WriteLine("Is locked: " & field.IsLocked)

' This updates only this field in the document.
field.Update()

See Also

FieldChar 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
[C#]
public class FieldCollection : IEnumerable

Remarks

An instance of this collection contains fields which starts fall within the specified range.

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;}

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.

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();

See Also

FieldCollection Class | Aspose.Words.Fields Namespace


FieldCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

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.

See Also

FieldCollection 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

Provides some helper functions by the methods above

[C#]

/// <summary>
/// Retrieves the field code from a field.
/// </summary>
/// <param name="fieldStart">The field start of the field which to gather the field code from</param>
/// <returns></returns>
private static string GetFieldCode(FieldStart fieldStart)
{
    StringBuilder builder = new StringBuilder();

    for (Node node = fieldStart; node != null && node.NodeType != NodeType.FieldSeparator &&
        node.NodeType != NodeType.FieldEnd; node = node.NextPreOrder(node.Document))
    {
        // Use text only of Run nodes to avoid duplication.
        if (node.NodeType == NodeType.Run)
            builder.Append(node.GetText());
    }
    return builder.ToString();
}

/// <summary>
/// Removes the Field from the document
/// </summary>
/// <param name="fieldStart">The field start node of the field to remove.</param>
private static void RemoveField(FieldStart fieldStart)
{
    Node currentNode = fieldStart;
    bool isRemoving = true;
    while (currentNode != null && isRemoving)
    {
        if (currentNode.NodeType == NodeType.FieldEnd)
            isRemoving = false;

        Node nextNode = currentNode.NextPreOrder(currentNode.Document);
        currentNode.Remove();
        currentNode = nextNode;
    }
}
[Visual Basic]

''' <summary>
''' Retrieves the field code from a field.
''' </summary>
''' <param name="fieldStart">The field start of the field which to gather the field code from</param>
''' <returns></returns>
Private Shared Function GetFieldCode(ByVal fieldStart As FieldStart) As String
    Dim builder As New StringBuilder()

    Dim node As Node = fieldStart
    Do While node IsNot Nothing AndAlso node.NodeType <> NodeType.FieldSeparator AndAlso node.NodeType <> NodeType.FieldEnd
        ' Use text only of Run nodes to avoid duplication.
        If node.NodeType = NodeType.Run Then
            builder.Append(node.GetText())
        End If
        node = node.NextPreOrder(node.Document)
    Loop
    Return builder.ToString()
End Function

''' <summary>
''' Removes the Field from the document
''' </summary>
''' <param name="fieldStart">The field start node of the field to remove.</param>
Private Shared Sub RemoveField(ByVal fieldStart As FieldStart)
    Dim currentNode As Node = fieldStart
    Dim isRemoving As Boolean = True
    Do While currentNode IsNot Nothing AndAlso isRemoving
        If currentNode.NodeType = NodeType.FieldEnd Then
            isRemoving = False
        End If

        Dim nextNode As Node = currentNode.NextPreOrder(currentNode.Document)
        currentNode.Remove()
        currentNode = nextNode
    Loop
End Sub

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.
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).
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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
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).
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;}

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

See Also

FieldEnd 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 string[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });
[Visual Basic]

' Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode
doc.MailMerge.Execute(New String() { "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

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.
FieldUpdateCultureSource | Specifies what culture to use to format the field result.
IsBidiTextSupportedOnUpdate | Gets or sets the value indicating whether bidirectional text is fully supported during field update 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

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.
FieldUpdateCultureSource | Specifies what culture to use to format the field result.
IsBidiTextSupportedOnUpdate | Gets or sets the value indicating whether bidirectional text is fully supported during field update or not.
UserPromptRespondent | Gets or sets the respondent to user prompts during field update.

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.

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;}

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 string[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });
[Visual Basic]

' Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode
doc.MailMerge.Execute(New String() { "Date2" }, New Object() { New DateTime(2011, 1, 01) })

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.

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.

See Also

FieldOptions 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

Provides some helper functions by the methods above

[C#]

/// <summary>
/// Retrieves the field code from a field.
/// </summary>
/// <param name="fieldStart">The field start of the field which to gather the field code from</param>
/// <returns></returns>
private static string GetFieldCode(FieldStart fieldStart)
{
    StringBuilder builder = new StringBuilder();

    for (Node node = fieldStart; node != null && node.NodeType != NodeType.FieldSeparator &&
        node.NodeType != NodeType.FieldEnd; node = node.NextPreOrder(node.Document))
    {
        // Use text only of Run nodes to avoid duplication.
        if (node.NodeType == NodeType.Run)
            builder.Append(node.GetText());
    }
    return builder.ToString();
}

/// <summary>
/// Removes the Field from the document
/// </summary>
/// <param name="fieldStart">The field start node of the field to remove.</param>
private static void RemoveField(FieldStart fieldStart)
{
    Node currentNode = fieldStart;
    bool isRemoving = true;
    while (currentNode != null && isRemoving)
    {
        if (currentNode.NodeType == NodeType.FieldEnd)
            isRemoving = false;

        Node nextNode = currentNode.NextPreOrder(currentNode.Document);
        currentNode.Remove();
        currentNode = nextNode;
    }
}
[Visual Basic]

''' <summary>
''' Retrieves the field code from a field.
''' </summary>
''' <param name="fieldStart">The field start of the field which to gather the field code from</param>
''' <returns></returns>
Private Shared Function GetFieldCode(ByVal fieldStart As FieldStart) As String
    Dim builder As New StringBuilder()

    Dim node As Node = fieldStart
    Do While node IsNot Nothing AndAlso node.NodeType <> NodeType.FieldSeparator AndAlso node.NodeType <> NodeType.FieldEnd
        ' Use text only of Run nodes to avoid duplication.
        If node.NodeType = NodeType.Run Then
            builder.Append(node.GetText())
        End If
        node = node.NextPreOrder(node.Document)
    Loop
    Return builder.ToString()
End Function

''' <summary>
''' Removes the Field from the document
''' </summary>
''' <param name="fieldStart">The field start node of the field to remove.</param>
Private Shared Sub RemoveField(ByVal fieldStart As FieldStart)
    Dim currentNode As Node = fieldStart
    Dim isRemoving As Boolean = True
    Do While currentNode IsNot Nothing AndAlso isRemoving
        If currentNode.NodeType = NodeType.FieldEnd Then
            isRemoving = False
        End If

        Dim nextNode As Node = currentNode.NextPreOrder(currentNode.Document)
        currentNode.Remove()
        currentNode = nextNode
    Loop
End Sub

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.
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).
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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
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).
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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

See Also

FieldSeparator 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

Provides some helper functions by the methods above

[C#]

/// <summary>
/// Retrieves the field code from a field.
/// </summary>
/// <param name="fieldStart">The field start of the field which to gather the field code from</param>
/// <returns></returns>
private static string GetFieldCode(FieldStart fieldStart)
{
    StringBuilder builder = new StringBuilder();

    for (Node node = fieldStart; node != null && node.NodeType != NodeType.FieldSeparator &&
        node.NodeType != NodeType.FieldEnd; node = node.NextPreOrder(node.Document))
    {
        // Use text only of Run nodes to avoid duplication.
        if (node.NodeType == NodeType.Run)
            builder.Append(node.GetText());
    }
    return builder.ToString();
}

/// <summary>
/// Removes the Field from the document
/// </summary>
/// <param name="fieldStart">The field start node of the field to remove.</param>
private static void RemoveField(FieldStart fieldStart)
{
    Node currentNode = fieldStart;
    bool isRemoving = true;
    while (currentNode != null && isRemoving)
    {
        if (currentNode.NodeType == NodeType.FieldEnd)
            isRemoving = false;

        Node nextNode = currentNode.NextPreOrder(currentNode.Document);
        currentNode.Remove();
        currentNode = nextNode;
    }
}
[Visual Basic]

''' <summary>
''' Retrieves the field code from a field.
''' </summary>
''' <param name="fieldStart">The field start of the field which to gather the field code from</param>
''' <returns></returns>
Private Shared Function GetFieldCode(ByVal fieldStart As FieldStart) As String
    Dim builder As New StringBuilder()

    Dim node As Node = fieldStart
    Do While node IsNot Nothing AndAlso node.NodeType <> NodeType.FieldSeparator AndAlso node.NodeType <> NodeType.FieldEnd
        ' Use text only of Run nodes to avoid duplication.
        If node.NodeType = NodeType.Run Then
            builder.Append(node.GetText())
        End If
        node = node.NextPreOrder(node.Document)
    Loop
    Return builder.ToString()
End Function

''' <summary>
''' Removes the Field from the document
''' </summary>
''' <param name="fieldStart">The field start node of the field to remove.</param>
Private Shared Sub RemoveField(ByVal fieldStart As FieldStart)
    Dim currentNode As Node = fieldStart
    Dim isRemoving As Boolean = True
    Do While currentNode IsNot Nothing AndAlso isRemoving
        If currentNode.NodeType = NodeType.FieldEnd Then
            isRemoving = False
        End If

        Dim nextNode As Node = currentNode.NextPreOrder(currentNode.Document)
        currentNode.Remove()
        currentNode = nextNode
    Loop
End Sub
Finds all hyperlinks in a Word document and changes their URL and display name.
[C#]

using System;
using System.Text;
using System.Text.RegularExpressions;
using Aspose.Words;
using Aspose.Words.Fields;

namespace Examples
{
    /// <summary>
    /// Shows how to replace hyperlinks in a Word document.
    /// </summary>
    public class ExReplaceHyperlinks : ExBase
    {
        /// <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)
            {
                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(MyDir + "ReplaceHyperlinks Out.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
            {
                string dummy = null;  // This is needed to fool the C# to VB.NET converter.
                return mTarget;
            }
            set
            {
                mTarget = value;
                UpdateFieldCode();
            }
        }

        /// <summary>
        /// True if the hyperlink's 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
            );
    }
}
[Visual Basic]

Imports Microsoft.VisualBasic
Imports System
Imports System.Text
Imports System.Text.RegularExpressions
Imports Aspose.Words
Imports Aspose.Words.Fields

Namespace Examples
    ''' <summary>
    ''' Shows how to replace hyperlinks in a Word document.
    ''' </summary>
    <TestFixture> _
    Public Class ExReplaceHyperlinks
        Inherits ExBase
        ''' <summary>
        ''' Finds all hyperlinks in a Word document and changes their URL and display name.
        ''' </summary>
        <Test> _
        Public Sub ReplaceHyperlinks()
            ' Specify your document name here.
            Dim doc As New Document(MyDir & "ReplaceHyperlinks.doc")

            ' Hyperlinks in a Word documents are fields, select all field start nodes so we can find the hyperlinks.
            Dim fieldStarts As NodeList = doc.SelectNodes("//FieldStart")
            For Each fieldStart As FieldStart In fieldStarts
                If fieldStart.FieldType.Equals(FieldType.FieldHyperlink) Then
                    ' The field is a hyperlink field, use the "facade" class to help to deal with the field.
                    Dim hyperlink As New Hyperlink(fieldStart)

                    ' Some hyperlinks can be local (links to bookmarks inside the document), ignore these.
                    If hyperlink.IsLocal Then
                        Continue For
                    End If

                    ' 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
                End If
            Next fieldStart

            doc.Save(MyDir & "ReplaceHyperlinks Out.doc")
        End Sub

        Private Const NewUrl As String = "http://www.aspose.com"
        Private Const NewName As String = "Aspose - The .NET & Java Component Publisher"
    End Class

    ''' <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>
    Friend Class Hyperlink
        Friend Sub New(ByVal fieldStart As FieldStart)
            If fieldStart Is Nothing Then
                Throw New ArgumentNullException("fieldStart")
            End If
            If (Not fieldStart.FieldType.Equals(FieldType.FieldHyperlink)) Then
                Throw New ArgumentException("Field start type must be FieldHyperlink.")
            End If

            mFieldStart = fieldStart

            ' Find the field separator node.
            mFieldSeparator = FindNextSibling(mFieldStart, NodeType.FieldSeparator)
            If mFieldSeparator Is Nothing Then
                Throw New InvalidOperationException("Cannot find field separator.")
            End If

            ' 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.
            Dim fieldCode As String = GetTextSameParent(mFieldStart.NextSibling, mFieldSeparator)
            Dim match As 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
        End Sub

        ''' <summary>
        ''' Gets or sets the display name of the hyperlink.
        ''' </summary>
        Friend Property Name() As String
            Get
                Return GetTextSameParent(mFieldSeparator, mFieldEnd)
            End Get
            Set(ByVal value As String)
                ' Hyperlink display name is stored in the field result which is a Run
                ' node between field separator and field end.
                Dim fieldResult As Run = CType(mFieldSeparator.NextSibling, Run)
                fieldResult.Text = value

                ' But sometimes the field result can consist of more than one run, delete these runs.
                RemoveSameParent(fieldResult.NextSibling, mFieldEnd)
            End Set
        End Property

        ''' <summary>
        ''' Gets or sets the target url or bookmark name of the hyperlink.
        ''' </summary>
        Friend Property Target() As String
            Get
                Dim dummy As String = Nothing ' This is needed to fool the C# to VB.NET converter.
                Return mTarget
            End Get
            Set(ByVal value As String)
                mTarget = value
                UpdateFieldCode()
            End Set
        End Property

        ''' <summary>
        ''' True if the hyperlink's target is a bookmark inside the document. False if the hyperlink is a url.
        ''' </summary>
        Friend Property IsLocal() As Boolean
            Get
                Return mIsLocal
            End Get
            Set(ByVal value As Boolean)
                mIsLocal = value
                UpdateFieldCode()
            End Set
        End Property

        Private Sub UpdateFieldCode()
            ' Field code is stored in a Run node between field start and field separator.
            Dim fieldCode As Run = CType(mFieldStart.NextSibling, Run)
            fieldCode.Text = String.Format("HYPERLINK {0}""{1}""", (If((mIsLocal), "\l ", "")), mTarget)

            ' But sometimes the field code can consist of more than one run, delete these runs.
            RemoveSameParent(fieldCode.NextSibling, mFieldSeparator)
        End Sub

        ''' <summary>
        ''' Goes through siblings starting from the start node until it finds a node of the specified type or null.
        ''' </summary>
        Private Shared Function FindNextSibling(ByVal startNode As Node, ByVal nodeType As NodeType) As Node
            Dim node As Node = startNode
            Do While node IsNot Nothing
                If node.NodeType.Equals(nodeType) Then
                    Return node
                End If
                node = node.NextSibling
            Loop
            Return Nothing
        End Function

        ''' <summary>
        ''' Retrieves text from start up to but not including the end node.
        ''' </summary>
        Private Shared Function GetTextSameParent(ByVal startNode As Node, ByVal endNode As Node) As String
            If (endNode IsNot Nothing) AndAlso (startNode.ParentNode IsNot endNode.ParentNode) Then
                Throw New ArgumentException("Start and end nodes are expected to have the same parent.")
            End If

            Dim builder As New StringBuilder()
            Dim child As Node = startNode
            Do While Not child.Equals(endNode)
                builder.Append(child.GetText())
                child = child.NextSibling
            Loop

            Return builder.ToString()
        End Function

        ''' <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 Shared Sub RemoveSameParent(ByVal startNode As Node, ByVal endNode As Node)
            If (endNode IsNot Nothing) AndAlso (startNode.ParentNode IsNot endNode.ParentNode) Then
                Throw New ArgumentException("Start and end nodes are expected to have the same parent.")
            End If

            Dim curChild As Node = startNode
            Do While (curChild IsNot Nothing) AndAlso (curChild IsNot endNode)
                Dim nextChild As Node = curChild.NextSibling
                curChild.Remove()
                curChild = nextChild
            Loop
        End Sub

        Private ReadOnly mFieldStart As Node
        Private ReadOnly mFieldSeparator As Node
        Private ReadOnly mFieldEnd As Node
        Private mIsLocal As Boolean
        Private mTarget As String

        ''' <summary>
        ''' RK I am notoriously bad at regexes. It seems I don't understand their way of thinking.
        ''' </summary>
        Private Shared ReadOnly gRegex As New Regex("\S+" & "\s+" & "(?:""""\s+)?" & "(\\l\s+)?" & """" &                  "([^""]+)" &          """"                )
    End Class
End Namespace

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.
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).
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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
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).
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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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) | Creates a duplicate of the 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

See Also

FieldStart Class | Aspose.Words.Fields Namespace


FieldType Enumeration

Enumeration that identifies all different types of Word fields.

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

Example

Shows how to find the type of field that is represented by a node which is derived from FieldChar.

[C#]

FieldChar fieldStart = (FieldChar)doc.GetChild(NodeType.FieldStart, 0, true);
FieldType type = fieldStart.FieldType;
[Visual Basic]

Dim fieldStart As FieldChar = CType(doc.GetChild(NodeType.FieldStart, 0, True), FieldChar)
Dim type As FieldType = fieldStart.FieldType
Inserts a field into a document using DocumentBuilder.
[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 behaviour 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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.
Dim dateField As Field = 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 behaviour 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 that the field contains data created by an add-in. | 81
FieldAddressBlock | Inserts an address block. | 93
FieldAdvance | Offset subsequent text within a line to the left, right, up or down. | 84
FieldAsk | Prompt the user for text to assign to a bookmark. | 38
FieldAuthor | The name of the document's author from Summary Info. | 17
FieldAutoNum | Insert an automatic number. | 54
FieldAutoNumLegal | Insert an automatic number in legal format. | 53
FieldAutoNumOutline | Insert an automatic number in outline format. | 52
FieldAutoText | Insert an AutoText entry. | 79
FieldAutoTextList | Insert text based on style. | 89
FieldBarCode | Insert a delivery point barcode. | 63
FieldBibliography | Inserts a Bibliography part. | 100500
FieldBidiOutline | Specified in [ECMA-376] part 4, section 2.16.5.12 | 92
FieldCitation | Inserts a Citation part. | 1980
FieldComments | The comments from Summary Info. | 19
FieldCompare | Compares two values. | 80
FieldCreateDate | The date the document was created. | 21
FieldData | Specifies that this field should redirect the mail merge data and header files to the ones specified. | 40
FieldDatabase | Insert data from an external database. | 78
FieldDate | Today's date. | 31
FieldDDE | Undocumented. | 45
FieldDDEAuto | Undocumented. | 46
FieldDocProperty | Insert the value of the property. | 85
FieldDocVariable | Insert the value of the document variable. | 64
FieldEditTime | The total document editing time. | 25
FieldEmbed | OLE2 embedded object. Might occur only in files. In the document object, represented by a single shape node. | 58
FieldEquation | Create a scientific equation. | 49
FieldFileName | The document's name and location. | 29
FieldFileSize | The size on disk of the active document. | 69
FieldFillIn | Prompt the user for text to insert in the document. | 39
FieldFootnoteRef | This field is identical to NOTEREF specified in [ECMA-376] part 4, section 2.16.5.47. | 5
FieldFormCheckBox | Check box control. | 71
FieldFormDropDown | Drop down control. | 83
FieldFormTextInput | Text control. | 70
FieldFormula | Calculates the result of an expression. | 34
FieldGreetingLine | Specified in [ECMA-376] part 4, section 2.16.5.30 | 94
FieldGlossary | This field is identical to AUTOTEXT specified in [ECMA-376] part 4, section 2.16.5.8 | 47
FieldGoToButton | Move the insertion point to a new location. | 50
FieldHtmlActiveX | Specifies the field represents an HTML control. | 91
FieldHyperlink | Open and jump to the specified file. | 88
FieldIf | Evaluate arguments conditionally. | 7
FieldInclude | This field is identical to INCLUDETEXT specified in [ECMA-376] part 4, section 2.16.5.34 | 36
FieldIncludePicture | "INCLUDEPICTURE", Insert a picture from a file. Might occur only in files. In the document object, represented by a single shape node. | 67
FieldIncludeText | Insert text from a file. | 68
FieldIndex | Create an index. | 8
FieldIndexEntry | Mark an index entry. | 4
FieldInfo | Data from Summary Info. | 14
FieldImport | Specified in [ECMA-376] part 4, section 2.16.5.33 | 55
FieldKeyword | The keywords from Summary Info. | 18
FieldLastSavedBy | Name of user who last saved the document. | 20
FieldLink | Linked OLE2 object. The LINK field in the file can be with an image or without. Aspose.Words represents a LINK field with an image and without differently in the model. A LINK field with an image will be represented by a Shape object and no field. A LINK field without an image will be represented as a normal field. | 56
FieldListNum | Insert an element in a list. | 90
FieldMacroButton | Run a macro. | 51
FieldMergeField | Insert a mail merge field. | 59
FieldMergeRec | The number of the current merge record. | 44
FieldMergeSeq | Merge record sequence number. | 75
FieldNext | Go to the next record in a mail merge. | 41
FieldNextIf | Conditionally go to the next record in a mail merge. | 42
FieldNoteRef | Insert the number of a footnote or endnote. | 72
FieldNumChars | The number of characters in the document. | 28
FieldNumPages | The number of pages in the document. | 26
FieldNumWords | The number of words in the document. | 27
FieldOcx | Represents an ActiveX control such as a command button etc. 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 | Insert the number of the current page. | 33
FieldPageRef | Insert the number of the page containing the specified bookmark. | 37
FieldPrint | Download commands to a printer. | 48
FieldPrintDate | The date the document was last printed. | 23
FieldPrivate | Stores data for documents converted from other file formats. Microsoft Word inserts a PRIVATE field when converting file formats; the field contains data needed for converting a document back to its original file format. A PRIVATE field is formatted as hidden text and doesn't affect the document layout. | 77
FieldQuote | Insert literal text. | 35
FieldRef | Insert the text marked by a bookmark. | 3
FieldRefNoKeyword | Specifies that the field represents a REF field where the keyword has been omitted. | 2
FieldRefDoc | Create an index, table of contents, table of figures, and/or table of authorities by using multiple documents. | 11
FieldRevisionNum | Insert the number of times the document has been saved. | 24
FieldSaveDate | The date the document was last saved. | 22
FieldSection | Insert the number of the current section. | 65
FieldSectionPages | Insert the total number of pages in the section. | 66
FieldSequence | Insert an automatic sequence number. | 12
FieldSet | Assign new text to a bookmark. | 6
FieldShape | Represents an inline shape in the document. Might occur only in files. In the document object, represented by a single shape node. | 95
FieldSkipIf | Conditionally skip a record in a mail merge. | 43
FieldStyleRef | Insert the text from a like-style paragraph. | 10
FieldSubject | The document's subject from Summary Info. | 16
FieldSymbol | Insert a special character. | 57
FieldTemplate | The name of the template attached to the document. | 30
FieldTime | The current time. | 32
FieldTitle | The document's title from Summary Info. | 15
FieldTOA | Create a table of authorities. | 73
FieldTOAEntry | Make a table of authorities entry. | 74
FieldTOC | Create a table of contents. | 13
FieldTOCEntry | Make a table of contents entry. | 9
FieldUserAddress | Address from Tools Options User Info. | 62
FieldUserInitials | Initials form Tools Options User Info. | 61
FieldUserName | Name from Tools Options User Info. | 60

Requirements

Namespace: Aspose.Words.Fields

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

See Also

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 string[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });
[Visual Basic]

' Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode
doc.MailMerge.Execute(New String() { "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


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;
[Visual Basic]

Dim doc As New Document(MyDir & "FormFields.doc")

Dim formField As FormField = doc.Range.FormFields(3)

If formField.Type.Equals(FieldType.FieldFormTextInput) Then
    formField.Result = "My name is " & formField.Name
End If
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"];
[Visual Basic]

Dim doc As New Document(MyDir & "FormFields.doc")
Dim documentFormFields As FormFieldCollection = doc.Range.FormFields

Dim formField1 As FormField = documentFormFields(3)
Dim formField2 As FormField = 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.
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.
IsInsertRevision (inherited from Inline) | Returns true if this object was 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) | Creates a duplicate of the 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.
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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
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.
IsInsertRevision (inherited from Inline) | Returns true if this object was 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.

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.

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.

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

Remarks

Applicable for a check box form field only.

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.

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;}

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.

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.

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.

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.

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.

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;}

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;}

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;
[Visual Basic]

Dim doc As New Document(MyDir & "FormFields.doc")

Dim formField As FormField = doc.Range.FormFields(3)

If formField.Type.Equals(FieldType.FieldFormTextInput) Then
    formField.Result = "My name is " & formField.Name
End If

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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.

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.

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;
[Visual Basic]

Dim doc As New Document(MyDir & "FormFields.doc")

Dim formField As FormField = doc.Range.FormFields(3)

If formField.Type.Equals(FieldType.FieldFormTextInput) Then
    formField.Result = "My name is " & formField.Name
End If

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.

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.

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.

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;}

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;
[Visual Basic]

Dim doc As New Document(MyDir & "FormFields.doc")

Dim formField As FormField = doc.Range.FormFields(3)

If formField.Type.Equals(FieldType.FieldFormTextInput) Then
    formField.Result = "My name is " & formField.Name
End If

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) | Creates a duplicate of the 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.
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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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.

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
[C#]
public class FormFieldCollection : IEnumerable

Example

Shows how to get a collection of form fields.

[C#]

Document doc = new Document(MyDir + "FormFields.doc");
FormFieldCollection formFields = doc.Range.FormFields;
[Visual Basic]

Dim doc As New Document(MyDir & "FormFields.doc")
Dim formFields As FormFieldCollection = 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 | Overloaded. Removes the specified form field from the document.
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;}

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.

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.

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 | Overloaded. Removes the specified form field from the document.
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();

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


FormFieldCollection.GetEnumerator Method

Returns an enumerator object.

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


Remove Method

Aspose.Words

FormFieldCollection.Remove Method

Removes the specified form field from the document.

Overload List

Removes the specified form field from the document.

public void Remove(FormField);

Removes a form field with the specified name.

public void Remove(string);

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace


FormFieldCollection.Remove Method (FormField)

Removes the specified form field from the document.

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

Parameters

formField
The formField to remove.

Remarks

If there is a bookmark associated with the form field, the bookmark is not removed.

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace | FormFieldCollection.Remove Overload List


FormFieldCollection.Remove Method (String)

Removes a form field with the specified name.

[Visual Basic]
Overloads 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.

See Also

FormFieldCollection Class | Aspose.Words.Fields Namespace | FormFieldCollection.Remove Overload List


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.

See Also

FormFieldCollection Class | 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.

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).

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.

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.

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.

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;}

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.

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

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 = new string[]
    {
        "-- 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("");

// Insert a check box to ensure the form filler does look after his/her footwear.
builder.InsertCheckBox("", true, 0);
builder.Writeln("My boots are always polished and nice-looking.");

builder.Document.Save(MyDir + "DocumentBuilder.CreateForm Out.doc");
[Visual Basic]

Dim builder As 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("")

Dim items() As String = { "-- 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("")

' Insert a check box to ensure the form filler does look after his/her footwear.
builder.InsertCheckBox("", True, 0)
builder.Writeln("My boots are always polished and nice-looking.")

builder.Document.Save(MyDir & "DocumentBuilder.CreateForm Out.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


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
FileFontSource | Represents the single TrueType font file stored in the file system.
FolderFontSource | Represents the folder that contains TrueType font files.
FontInfo | Specifies information about a font used in the document.
FontInfoCollection | Represents a collection of fonts used in a document.
FontSettings | This class provides static methods that allow to specify the location of TrueType fonts that Aspose.Words will use when rendering documents to PDF, XPS, printing, imaging or embedding fonts into EPUB and other document formats that support embedded fonts.
FontSourceBase | This is an abstract base class for the classes that allow the user to specify various font sources.
MemoryFontSource | Represents the single TrueType font file stored in memory.
SystemFontSource | Represents all TrueType fonts installed to the system.

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.


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

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.

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

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

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 Constructor Ctor.

Public Instance Properties

FilePath | Path to the font file.
Type | Returns the type of the font source.

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace


FileFontSource Constructor

Ctor.

[Visual Basic]
Public Sub New( _
ByVal filePath As String _
)
[C#]
public FileFontSource(
string filePath
);

Parameters

filePath
Path to font file.

See Also

FileFontSource Class | Aspose.Words.Fonts Namespace


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.
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;}

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;}

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

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 Constructor Ctor.

Public Instance Properties

FolderPath | Path to the folder.
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


FolderFontSource Constructor

Ctor.

[Visual Basic]
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.

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace


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.
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;}

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;}

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;}

See Also

FolderFontSource Class | Aspose.Words.Fonts Namespace


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.

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++;
}
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

Dim fonts As FontInfoCollection = doc.FontInfos
Dim fontIndex As Integer = 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.
For Each info As FontInfo 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 += 1
Next info

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.

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;}

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;}

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++;
}
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

Dim fonts As FontInfoCollection = doc.FontInfos
Dim fontIndex As Integer = 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.
For Each info As FontInfo 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 += 1
Next info

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++;
}
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

Dim fonts As FontInfoCollection = doc.FontInfos
Dim fontIndex As Integer = 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.
For Each info As FontInfo 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 += 1
Next info

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.

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;}

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.

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
[C#]
public class FontInfoCollection : 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 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++;
}
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

Dim fonts As FontInfoCollection = doc.FontInfos
Dim fontIndex As Integer = 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.
For Each info As FontInfo 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 += 1
Next info

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.
Item | Overloaded. Provides access to the collection items.

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.
Item | Overloaded. Provides access to the collection items.

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;}

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.

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.

See Also

FontInfoCollection Class | Aspose.Words.Fonts Namespace | FontInfoCollection.Item Overload List


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.

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

See Also

FontInfoCollection 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.

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

This class provides static methods that allow to specify the location of TrueType fonts that Aspose.Words will use when rendering documents to PDF, XPS, printing, imaging or embedding fonts into EPUB and other document formats that support embedded fonts.

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 loads fonts and caches them in a static cache (e.g. shared between rendering of different documents). While setting the new location for fonts is safe at any time from any thread, it is recommended that you do not change the location of fonts while some documents might be in in the process of rendering. It is recommended that you set the location of fonts during program startup before rendering any documents.

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.SetFontsFolder(@"C:\MyFonts\", false);

doc.Save(MyDir + "Rendering.SetFontsFolder Out.pdf");
[Visual Basic]

Dim doc As 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.SetFontsFolder("C:\MyFonts\", False)

doc.Save(MyDir & "Rendering.SetFontsFolder Out.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.SetFontsFolders(new string[] {@"C:\MyFonts\", @"D:\Misc\Fonts\"}, true);

doc.Save(MyDir + "Rendering.SetFontsFolders Out.pdf");
[Visual Basic]

Dim doc As 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.SetFontsFolders(New String() {"C:\MyFonts\", "D:\Misc\Fonts\"}, True)

doc.Save(MyDir & "Rendering.SetFontsFolders Out.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.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.SetFontsSources(updatedFontSources);

doc.Save(MyDir + "Rendering.SetFontsFolders Out.pdf");
[Visual Basic]

Dim doc As 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.
Dim fontSources As New ArrayList(FontSettings.GetFontsSources())

' Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
Dim folderFontSource As 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.
Dim updatedFontSources() As FontSourceBase = CType(fontSources.ToArray(GetType(FontSourceBase)), FontSourceBase())

' Apply the new set of font sources to use.
FontSettings.SetFontsSources(updatedFontSources)

doc.Save(MyDir & "Rendering.SetFontsFolders Out.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

DefaultFontName Gets or sets the default font name.

Public Static (Shared) 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 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

DefaultFontName Gets or sets the default font name.

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


DefaultFontName Property

Aspose.Words

FontSettings.DefaultFontName Property

Gets or sets the default font name.

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

Remarks

The default font name is used when Aspose.Words can't find requested font in specified sources.

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.DefaultFontName = "Arial Unicode MS";

// Now the set default font is used in place of any missing fonts during any rendering calls.
doc.Save(MyDir + "Rendering.SetDefaultFont Out.pdf");
doc.Save(MyDir + "Rendering.SetDefaultFont Out.xps");
[Visual Basic]

Dim doc As 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.DefaultFontName = "Arial Unicode MS"

' Now the set default font is used in place of any missing fonts during any rendering calls.
doc.Save(MyDir & "Rendering.SetDefaultFont Out.pdf")
doc.Save(MyDir & "Rendering.SetDefaultFont Out.xps")

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 Static (Shared) 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 Shared Function GetFontsSources() As FontSourceBase()
[C#]
public static 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.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.SetFontsSources(updatedFontSources);

doc.Save(MyDir + "Rendering.SetFontsFolders Out.pdf");
[Visual Basic]

Dim doc As 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.
Dim fontSources As New ArrayList(FontSettings.GetFontsSources())

' Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
Dim folderFontSource As 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.
Dim updatedFontSources() As FontSourceBase = CType(fontSources.ToArray(GetType(FontSourceBase)), FontSourceBase())

' Apply the new set of font sources to use.
FontSettings.SetFontsSources(updatedFontSources)

doc.Save(MyDir & "Rendering.SetFontsFolders Out.pdf")

See Also

FontSettings Class | Aspose.Words.Fonts Namespace


FontSettings.ResetFontSources Method

Resets the fonts sources to the system default.

[Visual Basic]
Public Shared Sub ResetFontSources()
[C#]
public static void ResetFontSources();

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 Shared Sub SetFontsFolder( _
ByVal fontFolder As String, _
ByVal recursive As Boolean _
)
[C#]
public static 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.SetFontsFolder(@"C:\MyFonts\", false);

doc.Save(MyDir + "Rendering.SetFontsFolder Out.pdf");
[Visual Basic]

Dim doc As 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.SetFontsFolder("C:\MyFonts\", False)

doc.Save(MyDir & "Rendering.SetFontsFolder Out.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 Shared Sub SetFontsFolders( _
ByVal fontsFolders As String(), _
ByVal recursive As Boolean _
)
[C#]
public static 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.SetFontsFolders(new string[] {@"C:\MyFonts\", @"D:\Misc\Fonts\"}, true);

doc.Save(MyDir + "Rendering.SetFontsFolders Out.pdf");
[Visual Basic]

Dim doc As 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.SetFontsFolders(New String() {"C:\MyFonts\", "D:\Misc\Fonts\"}, True)

doc.Save(MyDir & "Rendering.SetFontsFolders Out.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 Shared Sub SetFontsSources( _
ByVal sources As FontSourceBase() _
)
[C#]
public static 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.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.SetFontsSources(updatedFontSources);

doc.Save(MyDir + "Rendering.SetFontsFolders Out.pdf");
[Visual Basic]

Dim doc As 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.
Dim fontSources As New ArrayList(FontSettings.GetFontsSources())

' Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
Dim folderFontSource As 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.
Dim updatedFontSources() As FontSourceBase = CType(fontSources.ToArray(GetType(FontSourceBase)), FontSourceBase())

' Apply the new set of font sources to use.
FontSettings.SetFontsSources(updatedFontSources)

doc.Save(MyDir & "Rendering.SetFontsFolders Out.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.SystemFontSource

[Visual Basic]
MustInherit Public Class FontSourceBase
[C#]
public abstract class FontSourceBase

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

Type Returns the type of the font 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

Type Returns the type of the font source.

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;}

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

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

Requirements

Namespace: Aspose.Words.Fonts

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

See Also

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

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 Constructor Ctor.

Public Instance Properties

FontData | Binary font data.
Type | Returns the type of the font source.

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace


MemoryFontSource Constructor

Ctor.

[Visual Basic]
Public Sub New( _
ByVal fontData As Byte() _
)
[C#]
public MemoryFontSource(
byte[] fontData
);

Parameters

fontData
Binary font data.

See Also

MemoryFontSource Class | Aspose.Words.Fonts Namespace


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.
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;}

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;}

See Also

MemoryFontSource 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

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 Instance Constructors

SystemFontSource Constructor Ctor.

Public Instance Properties

Type Returns the type of the font source.

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace


SystemFontSource Constructor

Ctor.

[Visual Basic]
Public Sub New()
[C#]
public SystemFontSource();

See Also

SystemFontSource Class | Aspose.Words.Fonts Namespace


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

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;}

See Also

SystemFontSource 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 collects mapping of document nodes to layout objects and computes page numbers of nodes.

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.

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 MoveNode method to locate 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.


LayoutCollector Class

This class collects mapping of document nodes to layout objects and computes page numbers of nodes.

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.

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

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.

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.

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();

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
);

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.

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
);

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
);

See Also

LayoutCollector Class | Aspose.Words.Layout Namespace


LayoutEntityType Enumeration

Types of the layout entities.

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

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 MoveNode method to locate 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

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.
MoveNode | Obsolete.
MoveParent | Overloaded. Moves to the parent entity.
MovePrevious | Moves to the previous sibling entity.
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.

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;}

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;}

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.

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;}

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;}

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;}

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;}

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.
MoveNode | Obsolete.
MoveParent | Overloaded. Moves to the parent entity.
MovePrevious | Moves to the previous sibling entity.
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();

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();

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.MoveNext Method

Moves to the next sibling entity.

[Visual Basic]
Public Function MoveNext() As Boolean
[C#]
public bool MoveNext();

See Also

LayoutEnumerator Class | Aspose.Words.Layout Namespace


LayoutEnumerator.MoveNode Method

NOTE: This method is now obsolete.

[Visual Basic]
Public Function MoveNode( _
ByVal node As Node _
) As Boolean
[C#]
public bool MoveNode(
Node node
);

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();

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.

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();

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();

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.

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 Holds options related to layout of revisions.

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 Holds options related to layout of revisions.

See Also

LayoutOptions Class | Aspose.Words.Layout Namespace


RevisionOptions Property

Aspose.Words

LayoutOptions.RevisionOptions Property

Holds options related to layout of revisions.

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

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

Members

Member Name | Description | Value
Auto |  | 0
Black |  | 1
Blue |  | 2
BrightGreen |  | 3
DarkBlue |  | 4
DarkRed |  | 5
DarkYellow |  | 6
Gray25 |  | 7
Gray50 |  | 8
Green |  | 9
Pink |  | 10
Red |  | 11
Teal |  | 12
Turquoise |  | 13
Violet |  | 14
White |  | 15
Yellow |  | 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

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

DeletedTextColor | Allows to specify the color to be used for deleted content Deletion. Default value for this property is ByAuthor.
InsertedTextColor | Allows to specify the color to be used for inserted content Insertion. Default value for this property is ByAuthor.
RevisedPropertiesColor | Allows to specify the color to be used for content with changes of formatting properties FormatChange Default value for this property is NoHighlight.
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.

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

DeletedTextColor | Allows to specify the color to be used for deleted content Deletion. Default value for this property is ByAuthor.
InsertedTextColor | Allows to specify the color to be used for inserted content Insertion. Default value for this property is ByAuthor.
RevisedPropertiesColor | Allows to specify the color to be used for content with changes of formatting properties FormatChange Default value for this property is NoHighlight.
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.

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;}

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;}

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;}

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.

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;}

See Also

RevisionOptions Class | 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(MyDir + "Lists.SpecifyListLevel Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next i

' This is a way to stop list formatting.
builder.ListFormat.List = Nothing

builder.Document.Save(MyDir & "Lists.SpecifyListLevel Out.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.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(MyDir + "Lists.RestartNumberingUsingListCopy Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a list based on a template.
Dim list1 As Aspose.Words.Lists.List = 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.
Dim list2 As Aspose.Words.Lists.List = 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(MyDir & "Lists.RestartNumberingUsingListCopy Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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.
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

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.
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);

Aspose.Words.Lists.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] == list));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1) == list));
[Visual Basic]

Dim doc As New Document()

Dim lists As ListCollection = doc.Lists
' All of these should be equal.
Console.WriteLine("ListCollection document is doc: " & (doc Is lists.Document))
Console.WriteLine("Starting list count: " & lists.Count)

Dim list As Aspose.Words.Lists.List = lists.Add(ListTemplate.BulletDefault)
Console.WriteLine("List document is doc: " & (list.Document Is doc))
Console.WriteLine("List count after adding list: " & lists.Count)
Console.WriteLine("Is the first document list: " & (lists(0) Is list))
Console.WriteLine("ListId: " & list.ListId)
Console.WriteLine("List is the same by ListId: " & (lists.GetListByListId(1) Is 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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.doc")

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)
{
    if (para.ListFormat.IsListItem)
    {
        Console.WriteLine(string.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId));
        Console.WriteLine(para.GetText());
    }
}
[Visual Basic]

Dim paras As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
For Each para As Paragraph In paras
    If para.ListFormat.IsListItem Then
        Console.WriteLine(String.Format("*** A paragraph belongs to list {0}", para.ListFormat.List.ListId))
        Console.WriteLine(para.GetText())
    End If
Next para
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);

Aspose.Words.Lists.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] == list));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1) == list));
[Visual Basic]

Dim doc As New Document()

Dim lists As ListCollection = doc.Lists
' All of these should be equal.
Console.WriteLine("ListCollection document is doc: " & (doc Is lists.Document))
Console.WriteLine("Starting list count: " & lists.Count)

Dim list As Aspose.Words.Lists.List = lists.Add(ListTemplate.BulletDefault)
Console.WriteLine("List document is doc: " & (list.Document Is doc))
Console.WriteLine("List count after adding list: " & lists.Count)
Console.WriteLine("Is the first document list: " & (lists(0) Is list))
Console.WriteLine("ListId: " & list.ListId)
Console.WriteLine("List is the same by ListId: " & (lists.GetListByListId(1) Is 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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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

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


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
[C#]
public class ListCollection : 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(MyDir + "Lists.SpecifyListLevel Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next i

' This is a way to stop list formatting.
builder.ListFormat.List = Nothing

builder.Document.Save(MyDir & "Lists.SpecifyListLevel Out.doc")
Enumerates through all lists defined in one document and creates a sample of those lists in another document.
[C#]

public void PrintOutAllLists()
{
    // 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 (Aspose.Words.Lists.List srcList in srcDoc.Lists)
    {
        // This copies the list formatting from the source into the destination document.
        Aspose.Words.Lists.List dstList = dstDoc.Lists.AddCopy(srcList);
        AddListSample(builder, dstList);
    }

    dstDoc.Save(MyDir + "Lists.PrintOutAllLists Out.doc");
}

private static void AddListSample(DocumentBuilder builder, Aspose.Words.Lists.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();
}
[Visual Basic]

Public Sub PrintOutAllLists()
    ' You can use any of your documents to try this little program out.
    Dim srcDoc As New Document(MyDir & "Lists.PrintOutAllLists.doc")

    ' This will be the sample document we product.
    Dim dstDoc As New Document()
    Dim builder As New DocumentBuilder(dstDoc)

    For Each srcList As Aspose.Words.Lists.List In srcDoc.Lists
        ' This copies the list formatting from the source into the destination document.
        Dim dstList As Aspose.Words.Lists.List = dstDoc.Lists.AddCopy(srcList)
        AddListSample(builder, dstList)
    Next srcList

    dstDoc.Save(MyDir & "Lists.PrintOutAllLists Out.doc")
End Sub

Private Shared Sub AddListSample(ByVal builder As DocumentBuilder, ByVal list As Aspose.Words.Lists.List)
    builder.Writeln("Sample formatting of list with ListId:" & list.ListId)
    builder.ListFormat.List = list
    For i As Integer = 0 To list.ListLevels.Count - 1
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
    builder.ListFormat.RemoveNumbers()
    builder.Writeln()
End Sub
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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.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(MyDir + "Lists.RestartNumberingUsingListCopy Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a list based on a template.
Dim list1 As Aspose.Words.Lists.List = 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.
Dim list2 As Aspose.Words.Lists.List = 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(MyDir & "Lists.RestartNumberingUsingListCopy Out.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);

Aspose.Words.Lists.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] == list));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1) == list));
[Visual Basic]

Dim doc As New Document()

Dim lists As ListCollection = doc.Lists
' All of these should be equal.
Console.WriteLine("ListCollection document is doc: " & (doc Is lists.Document))
Console.WriteLine("Starting list count: " & lists.Count)

Dim list As Aspose.Words.Lists.List = lists.Add(ListTemplate.BulletDefault)
Console.WriteLine("List document is doc: " & (list.Document Is doc))
Console.WriteLine("List count after adding list: " & lists.Count)
Console.WriteLine("Is the first document list: " & (lists(0) Is list))
Console.WriteLine("ListId: " & list.ListId)
Console.WriteLine("List is the same by ListId: " & (lists.GetListByListId(1) Is 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);

Aspose.Words.Lists.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] == list));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1) == list));
[Visual Basic]

Dim doc As New Document()

Dim lists As ListCollection = doc.Lists
' All of these should be equal.
Console.WriteLine("ListCollection document is doc: " & (doc Is lists.Document))
Console.WriteLine("Starting list count: " & lists.Count)

Dim list As Aspose.Words.Lists.List = lists.Add(ListTemplate.BulletDefault)
Console.WriteLine("List document is doc: " & (list.Document Is doc))
Console.WriteLine("List count after adding list: " & lists.Count)
Console.WriteLine("Is the first document list: " & (lists(0) Is list))
Console.WriteLine("ListId: " & list.ListId)
Console.WriteLine("List is the same by ListId: " & (lists.GetListByListId(1) Is 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;
Aspose.Words.Lists.List list = doc.Lists[0];
foreach (Paragraph paragraph in body.Paragraphs)
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 2;
}
[Visual Basic]

Dim body As Body = doc.FirstSection.Body
Dim list As Aspose.Words.Lists.List = doc.Lists(0)
For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.List = list
    paragraph.ListFormat.ListLevelNumber = 2
Next paragraph
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);

Aspose.Words.Lists.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] == list));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1) == list));
[Visual Basic]

Dim doc As New Document()

Dim lists As ListCollection = doc.Lists
' All of these should be equal.
Console.WriteLine("ListCollection document is doc: " & (doc Is lists.Document))
Console.WriteLine("Starting list count: " & lists.Count)

Dim list As Aspose.Words.Lists.List = lists.Add(ListTemplate.BulletDefault)
Console.WriteLine("List document is doc: " & (list.Document Is doc))
Console.WriteLine("List count after adding list: " & lists.Count)
Console.WriteLine("Is the first document list: " & (lists(0) Is list))
Console.WriteLine("ListId: " & list.ListId)
Console.WriteLine("List is the same by ListId: " & (lists.GetListByListId(1) Is 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#]

Aspose.Words.Lists.List list = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot);

Body body = doc.FirstSection.Body;
foreach (Paragraph paragraph in body.Paragraphs)
{
    paragraph.ListFormat.List = list;
    paragraph.ListFormat.ListLevelNumber = 1;
}
[Visual Basic]

Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot)

Dim body As Body = doc.FirstSection.Body
For Each paragraph As Paragraph In body.Paragraphs
    paragraph.ListFormat.List = list
    paragraph.ListFormat.ListLevelNumber = 1
Next paragraph
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(MyDir + "Lists.SpecifyListLevel Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next i

' This is a way to stop list formatting.
builder.ListFormat.List = Nothing

builder.Document.Save(MyDir & "Lists.SpecifyListLevel Out.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.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(MyDir + "Lists.RestartNumberingUsingListCopy Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a list based on a template.
Dim list1 As Aspose.Words.Lists.List = 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.
Dim list2 As Aspose.Words.Lists.List = 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(MyDir & "Lists.RestartNumberingUsingListCopy Out.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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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#]

public void PrintOutAllLists()
{
    // 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 (Aspose.Words.Lists.List srcList in srcDoc.Lists)
    {
        // This copies the list formatting from the source into the destination document.
        Aspose.Words.Lists.List dstList = dstDoc.Lists.AddCopy(srcList);
        AddListSample(builder, dstList);
    }

    dstDoc.Save(MyDir + "Lists.PrintOutAllLists Out.doc");
}

private static void AddListSample(DocumentBuilder builder, Aspose.Words.Lists.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();
}
[Visual Basic]

Public Sub PrintOutAllLists()
    ' You can use any of your documents to try this little program out.
    Dim srcDoc As New Document(MyDir & "Lists.PrintOutAllLists.doc")

    ' This will be the sample document we product.
    Dim dstDoc As New Document()
    Dim builder As New DocumentBuilder(dstDoc)

    For Each srcList As Aspose.Words.Lists.List In srcDoc.Lists
        ' This copies the list formatting from the source into the destination document.
        Dim dstList As Aspose.Words.Lists.List = dstDoc.Lists.AddCopy(srcList)
        AddListSample(builder, dstList)
    Next srcList

    dstDoc.Save(MyDir & "Lists.PrintOutAllLists Out.doc")
End Sub

Private Shared Sub AddListSample(ByVal builder As DocumentBuilder, ByVal list As Aspose.Words.Lists.List)
    builder.Writeln("Sample formatting of list with ListId:" & list.ListId)
    builder.ListFormat.List = list
    For i As Integer = 0 To list.ListLevels.Count - 1
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
    builder.ListFormat.RemoveNumbers()
    builder.Writeln()
End Sub
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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.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(MyDir + "Lists.RestartNumberingUsingListCopy Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a list based on a template.
Dim list1 As Aspose.Words.Lists.List = 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.
Dim list2 As Aspose.Words.Lists.List = 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(MyDir & "Lists.RestartNumberingUsingListCopy Out.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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

Example

Enumerates through all lists defined in one document and creates a sample of those lists in another document.

[C#]

public void PrintOutAllLists()
{
    // 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 (Aspose.Words.Lists.List srcList in srcDoc.Lists)
    {
        // This copies the list formatting from the source into the destination document.
        Aspose.Words.Lists.List dstList = dstDoc.Lists.AddCopy(srcList);
        AddListSample(builder, dstList);
    }

    dstDoc.Save(MyDir + "Lists.PrintOutAllLists Out.doc");
}

private static void AddListSample(DocumentBuilder builder, Aspose.Words.Lists.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();
}
[Visual Basic]

Public Sub PrintOutAllLists()
    ' You can use any of your documents to try this little program out.
    Dim srcDoc As New Document(MyDir & "Lists.PrintOutAllLists.doc")

    ' This will be the sample document we product.
    Dim dstDoc As New Document()
    Dim builder As New DocumentBuilder(dstDoc)

    For Each srcList As Aspose.Words.Lists.List In srcDoc.Lists
        ' This copies the list formatting from the source into the destination document.
        Dim dstList As Aspose.Words.Lists.List = dstDoc.Lists.AddCopy(srcList)
        AddListSample(builder, dstList)
    Next srcList

    dstDoc.Save(MyDir & "Lists.PrintOutAllLists Out.doc")
End Sub

Private Shared Sub AddListSample(ByVal builder As DocumentBuilder, ByVal list As Aspose.Words.Lists.List)
    builder.Writeln("Sample formatting of list with ListId:" & list.ListId)
    builder.ListFormat.List = list
    For i As Integer = 0 To list.ListLevels.Count - 1
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
    builder.ListFormat.RemoveNumbers()
    builder.Writeln()
End Sub

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);

Aspose.Words.Lists.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] == list));
Console.WriteLine("ListId: " + list.ListId);
Console.WriteLine("List is the same by ListId: " + (lists.GetListByListId(1) == list));
[Visual Basic]

Dim doc As New Document()

Dim lists As ListCollection = doc.Lists
' All of these should be equal.
Console.WriteLine("ListCollection document is doc: " & (doc Is lists.Document))
Console.WriteLine("Starting list count: " & lists.Count)

Dim list As Aspose.Words.Lists.List = lists.Add(ListTemplate.BulletDefault)
Console.WriteLine("List document is doc: " & (list.Document Is doc))
Console.WriteLine("List count after adding list: " & lists.Count)
Console.WriteLine("Is the first document list: " & (lists(0) Is list))
Console.WriteLine("ListId: " & list.ListId)
Console.WriteLine("List is the same by ListId: " & (lists.GetListByListId(1) Is 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))
{
    // 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++;
    }

}
[Visual Basic]

Dim doc As New Document(MyDir & "Lists.PrintOutAllLists.doc")
doc.UpdateListLabels()
Dim listParaCount As Integer = 1

For Each paragraph As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 Then
        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.
        Dim paragraphText As String = paragraph.ToString(SaveFormat.Text).Trim()
        Console.WriteLine("Exported Text: " & paragraphText)

        Dim label As ListLabel = 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 += 1
    End If

Next paragraph

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))
{
    // 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++;
    }

}
[Visual Basic]

Dim doc As New Document(MyDir & "Lists.PrintOutAllLists.doc")
doc.UpdateListLabels()
Dim listParaCount As Integer = 1

For Each paragraph As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 Then
        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.
        Dim paragraphText As String = paragraph.ToString(SaveFormat.Text).Trim()
        Console.WriteLine("Exported Text: " & paragraphText)

        Dim label As ListLabel = 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 += 1
    End If

Next paragraph

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))
{
    // 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++;
    }

}
[Visual Basic]

Dim doc As New Document(MyDir & "Lists.PrintOutAllLists.doc")
doc.UpdateListLabels()
Dim listParaCount As Integer = 1

For Each paragraph As Paragraph In doc.GetChildNodes(NodeType.Paragraph, True)
    ' 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 Then
        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.
        Dim paragraphText As String = paragraph.ToString(SaveFormat.Text).Trim()
        Console.WriteLine("Exported Text: " & paragraphText)

        Dim label As ListLabel = 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 += 1
    End If

Next paragraph

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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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.
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


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.
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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.doc")

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);

Aspose.Words.Lists.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(MyDir + "Lists.CreateListRestartAfterHigher Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim list As Aspose.Words.Lists.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 " & ChrW(&H0000).ToString()
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 (" & ChrW(&H0000).ToString() & "." & ChrW(&H0001).ToString() & ")"
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 = "-" & ChrW(&H0002).ToString() & "-"
list.ListLevels(2).NumberStyle = NumberStyle.UppercaseRoman
list.ListLevels(2).RestartAfterLevel = 1

' Make labels of all list levels bold.
For Each level As ListLevel In list.ListLevels
    level.Font.Bold = True
Next level

' Apply list formatting to the current paragraph.
builder.ListFormat.List = list

' Exercise the 3 levels we created two times.
For n As Integer = 0 To 1
    For i As Integer = 0 To 2
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
Next n

builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateListRestartAfterHigher Out.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);

Aspose.Words.Lists.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(MyDir + "Lists.CreateListRestartAfterHigher Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim list As Aspose.Words.Lists.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 " & ChrW(&H0000).ToString()
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 (" & ChrW(&H0000).ToString() & "." & ChrW(&H0001).ToString() & ")"
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 = "-" & ChrW(&H0002).ToString() & "-"
list.ListLevels(2).NumberStyle = NumberStyle.UppercaseRoman
list.ListLevels(2).RestartAfterLevel = 1

' Make labels of all list levels bold.
For Each level As ListLevel In list.ListLevels
    level.Font.Bold = True
Next level

' Apply list formatting to the current paragraph.
builder.ListFormat.List = list

' Exercise the 3 levels we created two times.
For n As Integer = 0 To 1
    For i As Integer = 0 To 2
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
Next n

builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateListRestartAfterHigher Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.doc")
Shows how to create a list with some advanced formatting.
[C#]

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

Aspose.Words.Lists.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(MyDir + "Lists.CreateListRestartAfterHigher Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim list As Aspose.Words.Lists.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 " & ChrW(&H0000).ToString()
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 (" & ChrW(&H0000).ToString() & "." & ChrW(&H0001).ToString() & ")"
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 = "-" & ChrW(&H0002).ToString() & "-"
list.ListLevels(2).NumberStyle = NumberStyle.UppercaseRoman
list.ListLevels(2).RestartAfterLevel = 1

' Make labels of all list levels bold.
For Each level As ListLevel In list.ListLevels
    level.Font.Bold = True
Next level

' Apply list formatting to the current paragraph.
builder.ListFormat.List = list

' Exercise the 3 levels we created two times.
For n As Integer = 0 To 1
    For i As Integer = 0 To 2
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
Next n

builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateListRestartAfterHigher Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.doc")
Shows how to create a list with some advanced formatting.
[C#]

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

Aspose.Words.Lists.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(MyDir + "Lists.CreateListRestartAfterHigher Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim list As Aspose.Words.Lists.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 " & ChrW(&H0000).ToString()
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 (" & ChrW(&H0000).ToString() & "." & ChrW(&H0001).ToString() & ")"
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 = "-" & ChrW(&H0002).ToString() & "-"
list.ListLevels(2).NumberStyle = NumberStyle.UppercaseRoman
list.ListLevels(2).RestartAfterLevel = 1

' Make labels of all list levels bold.
For Each level As ListLevel In list.ListLevels
    level.Font.Bold = True
Next level

' Apply list formatting to the current paragraph.
builder.ListFormat.List = list

' Exercise the 3 levels we created two times.
For n As Integer = 0 To 1
    For i As Integer = 0 To 2
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
Next n

builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateListRestartAfterHigher Out.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);

Aspose.Words.Lists.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(MyDir + "Lists.CreateListRestartAfterHigher Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim list As Aspose.Words.Lists.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 " & ChrW(&H0000).ToString()
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 (" & ChrW(&H0000).ToString() & "." & ChrW(&H0001).ToString() & ")"
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 = "-" & ChrW(&H0002).ToString() & "-"
list.ListLevels(2).NumberStyle = NumberStyle.UppercaseRoman
list.ListLevels(2).RestartAfterLevel = 1

' Make labels of all list levels bold.
For Each level As ListLevel In list.ListLevels
    level.Font.Bold = True
Next level

' Apply list formatting to the current paragraph.
builder.ListFormat.List = list

' Exercise the 3 levels we created two times.
For n As Integer = 0 To 1
    For i As Integer = 0 To 2
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
Next n

builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateListRestartAfterHigher Out.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.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(MyDir + "Lists.RestartNumberingUsingListCopy Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a list based on a template.
Dim list1 As Aspose.Words.Lists.List = 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.
Dim list2 As Aspose.Words.Lists.List = 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(MyDir & "Lists.RestartNumberingUsingListCopy Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.doc")

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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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
[C#]
public class ListLevelCollection : 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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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).
Aspose.Words.Lists.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.List list3 = doc.Lists.Add(listStyle);
builder.ListFormat.List = list3;
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.RemoveNumbers();

builder.Document.Save(MyDir + "Lists.CreateAndUseListStyle Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a new list style.
' List formatting associated with this list style is default numbered.
Dim listStyle As Style = 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).
Dim list1 As Aspose.Words.Lists.List = 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 Is list1.Style))

' Modify formatting of the list style to our liking.
For i As Integer = 0 To list1.ListLevels.Count - 1
    Dim level As ListLevel = list1.ListLevels(i)
    level.Font.Name = "Verdana"
    level.Font.Color = Color.Blue
    level.Font.Bold = True
Next i

' Add some text to our document and use the list style.
Dim builder As New DocumentBuilder(doc)

builder.Writeln("Using list style first time:")

' This creates a list based on the list style.
Dim list2 As Aspose.Words.Lists.List = 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 Is 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.
Dim list3 As Aspose.Words.Lists.List = doc.Lists.Add(listStyle)
builder.ListFormat.List = list3
builder.Writeln("Item 1")
builder.Writeln("Item 2")
builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateAndUseListStyle Out.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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

Example

Shows how to create a list with some advanced formatting.

[C#]

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

Aspose.Words.Lists.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(MyDir + "Lists.CreateListRestartAfterHigher Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim list As Aspose.Words.Lists.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 " & ChrW(&H0000).ToString()
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 (" & ChrW(&H0000).ToString() & "." & ChrW(&H0001).ToString() & ")"
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 = "-" & ChrW(&H0002).ToString() & "-"
list.ListLevels(2).NumberStyle = NumberStyle.UppercaseRoman
list.ListLevels(2).RestartAfterLevel = 1

' Make labels of all list levels bold.
For Each level As ListLevel In list.ListLevels
    level.Font.Bold = True
Next level

' Apply list formatting to the current paragraph.
builder.ListFormat.List = list

' Exercise the 3 levels we created two times.
For n As Integer = 0 To 1
    For i As Integer = 0 To 2
        builder.ListFormat.ListLevelNumber = i
        builder.Writeln("Level " & i)
    Next i
Next n

builder.ListFormat.RemoveNumbers()

builder.Document.Save(MyDir & "Lists.CreateListRestartAfterHigher Out.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(MyDir + "Lists.SpecifyListLevel Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next 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 i As Integer = 0 To 8
    builder.ListFormat.ListLevelNumber = i
    builder.Writeln("Level " & i)
Next i

' This is a way to stop list formatting.
builder.ListFormat.List = Nothing

builder.Document.Save(MyDir & "Lists.SpecifyListLevel Out.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.
Aspose.Words.Lists.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.
Aspose.Words.Lists.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(MyDir + "Lists.RestartNumberingUsingListCopy Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Create a list based on a template.
Dim list1 As Aspose.Words.Lists.List = 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.
Dim list2 As Aspose.Words.Lists.List = 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(MyDir & "Lists.RestartNumberingUsingListCopy Out.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);

    Aspose.Words.Lists.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(MyDir + "Lists.OutlineHeadingTemplates Out.doc");
}

private static void AddOutlineHeadingParagraphs(DocumentBuilder builder, Aspose.Words.Lists.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();
}
[Visual Basic]

Public Sub OutlineHeadingTemplates()
    Dim doc As New Document()
    Dim builder As New DocumentBuilder(doc)

    Dim list As Aspose.Words.Lists.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(MyDir & "Lists.OutlineHeadingTemplates Out.doc")
End Sub

Private Shared Sub AddOutlineHeadingParagraphs(ByVal builder As DocumentBuilder, ByVal list As Aspose.Words.Lists.List, ByVal title As String)
    builder.ParagraphFormat.ClearFormatting()
    builder.Writeln(title)

    For i As Integer = 0 To 8
        builder.ListFormat.List = list
        builder.ListFormat.ListLevelNumber = i

        Dim styleName As String = "Heading " & (i + 1).ToString()
        builder.ParagraphFormat.StyleName = styleName
        builder.Writeln(styleName)
    Next i

    builder.ListFormat.RemoveNumbers()
End Sub

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.
Aspose.Words.Lists.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(MyDir + "Lists.CreateCustomList Out.doc");
[Visual Basic]

Dim doc As New Document()

' Create a list based on one of the Microsoft Word list templates.
Dim list As Aspose.Words.Lists.List = doc.Lists.Add(ListTemplate.NumberDefault)

' Completely customize one list level.
Dim level1 As ListLevel = list.ListLevels(0)
level1.Font.Color = Color.Red
level1.Font.Size = 24
level1.NumberStyle = NumberStyle.OrdinalText
level1.StartAt = 21
level1.NumberFormat = ChrW(&H0000).ToString()

level1.NumberPosition = -36
level1.TextPosition = 144
level1.TabPosition = 144

' Completely customize yet another list level.
Dim level2 As ListLevel = 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 = ChrW(&Hf0af).ToString() ' 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.
Dim builder As 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(MyDir & "Lists.CreateCustomList Out.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

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
);

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

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

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;}

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;}

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
);

See Also

ResourceLoadingArgs Class | Aspose.Words.Loading Namespace


ResourceType Enumeration

Type of loaded resource.

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

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.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.
CustomXmlMarkup | This element specifies the presence of Custom XML markup around inline structures (runs, images, fields, etc.), paragraphs, tables, rows and cells.
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.

Enumerations

Enumeration | Description
MarkupLevel | Specifies the level in the document tree where a particular StructuredDocumentTag or CustomXmlMarkup 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.

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 an instance of this 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 an instance of this class.

[Visual Basic]
Public Sub New()
[C#]
public CustomPart();

Remarks

You can create CustomPart instances and add them to the PackageCustomParts collection.

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.

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.

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.

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.

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.

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();

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
[C#]
public class CustomPartCollection : 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.

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 this 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 this 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;}

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.

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.

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();

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();

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

See Also

CustomPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlMarkup Class

This element specifies the presence of Custom XML markup around inline structures (runs, images, fields, etc.), paragraphs, tables, rows and cells.

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

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode
Aspose.Words.Markup.CustomXmlMarkup

[Visual Basic]
Public Class CustomXmlMarkup
Inherits CompositeNode
[C#]
public class CustomXmlMarkup : CompositeNode

Remarks

Custom XML markup allows to define customer-specific semantics by applying XML elements defined by any schema syntax (XML Schema, NVDL, etc.)

CustomXmlMarkup can be placed 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 CustomXmlMarkup.

Requirements

Namespace: Aspose.Words.Markup

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

See Also

CustomXmlMarkup Members | Aspose.Words.Markup Namespace


CustomXmlMarkup Members

CustomXmlMarkup overview

Public Instance Constructors

CustomXmlMarkup Constructor Initializes a new instance of the CustomXmlMarkup 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 custom Xml markup element 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.
Level | Gets the level at which this Custom XML markup node occurs in the document tree.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.CustomXmlMarkup.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
Placeholder | Specifies the placeholder text which shall be displayed in place of this custom XML element when the contents of this custom XML markup are empty (i.e. there are no runs of text within the current custom XML element).
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Properties | A collection of the Custom XML markup node 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 Custom XML markup 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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


CustomXmlMarkup Constructor

Initializes a new instance of the CustomXmlMarkup class.

[Visual Basic]
Public Sub New( _
ByVal doc As DocumentBase, _
ByVal level As MarkupLevel _
)
[C#]
public CustomXmlMarkup(
DocumentBase doc,
MarkupLevel level
);

Parameters

doc
The owner document.
level
Level at which this markup node will be inserted.

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.

Upon creation of CustomXmlMarkup markup node it is required to specify the level at which it will be placed MarkupLevel. Aspose.Words verifies that when this node is inserted into the document tree, its MarkupLevel corresponds to the real location inside the tree.

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


CustomXmlMarkup Properties

The properties of the CustomXmlMarkup class are listed below. For a complete list of CustomXmlMarkup class members, see the CustomXmlMarkup 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 custom Xml markup element 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.
Level | Gets the level at which this Custom XML markup node occurs in the document tree.
NextSibling (inherited from Node) | Gets the node immediately following this node.
NodeType | Returns NodeType.CustomXmlMarkup.
ParentNode (inherited from Node) | Gets the immediate parent of this node.
Placeholder | Specifies the placeholder text which shall be displayed in place of this custom XML element when the contents of this custom XML markup are empty (i.e. there are no runs of text within the current custom XML element).
PreviousSibling (inherited from Node) | Gets the node immediately preceding this node.
Properties | A collection of the Custom XML markup node 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 Custom XML markup node.

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


Element Property

Aspose.Words

CustomXmlMarkup.Element Property

Specifies the name of the custom Xml markup element within the document.

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

Remarks

Cannot be null.

Default is empty string.

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


Level Property

Aspose.Words

CustomXmlMarkup.Level Property

Gets the level at which this Custom XML markup node occurs in the document tree.

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

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


NodeType Property

Aspose.Words

CustomXmlMarkup.NodeType Property

Returns NodeType.CustomXmlMarkup.

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

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


Placeholder Property

Aspose.Words

CustomXmlMarkup.Placeholder Property

Specifies the placeholder text which shall be displayed in place of this custom XML element when the contents of this custom XML markup are empty (i.e. there are no runs of text within the current custom XML element).

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

Remarks

If this custom XML element does contain run content, then this text shall not be displayed.

Default is empty string.

Cannot be null.

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


Properties Property

Aspose.Words

CustomXmlMarkup.Properties Property

A collection of the Custom XML markup node properties.

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

Remarks

Cannot be null.

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


Uri Property

Aspose.Words

CustomXmlMarkup.Uri Property

Specifies the namespace URI of the Custom XML markup node.

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

Remarks

Cannot be null.

Default is empty string.

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


CustomXmlMarkup Methods

The methods of the CustomXmlMarkup class are listed below. For a complete list of CustomXmlMarkup class members, see the CustomXmlMarkup 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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text format.

See Also

CustomXmlMarkup Class | Aspose.Words.Markup Namespace


CustomXmlMarkup.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 VisitCustomXmlMarkupStart, then calls Accept for all child nodes of the custom Xml node and calls VisitCustomXmlMarkupEnd at the end.

See Also

CustomXmlMarkup 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.

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 an instance of this 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 an instance of this 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.

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 Microsoft Word seems to allow any string value for this property and Aspose.Words does the same. 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.

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;}

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();

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
[C#]
public class CustomXmlPartCollection : 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.

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 an instance of this 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.
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 an instance of this 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;}

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.

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 | 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.Add Method

Adds an item to the collection.

[Visual Basic]
Public Sub Add( _
ByVal part As CustomXmlPart _
)
[C#]
public void Add(
CustomXmlPart part
);

Parameters

part
The custom XML part to add.

See Also

CustomXmlPartCollection Class | Aspose.Words.Markup Namespace


CustomXmlPartCollection.Clear Method

Removes all elements from the collection.

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

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();

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.

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

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.

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.

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.

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.

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.

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
[C#]
public class CustomXmlPropertyCollection : IEnumerable

Remarks

Items are CustomXmlProperty objects.

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;}

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.

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.

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.

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();

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.

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

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.

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.

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
[C#]
public class CustomXmlSchemaCollection : 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.

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;}

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;}

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.

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();

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();

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

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.

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.

See Also

CustomXmlSchemaCollection Class | Aspose.Words.Markup Namespace


MarkupLevel Enumeration

Specifies the level in the document tree where a particular StructuredDocumentTag or CustomXmlMarkup can occur.

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

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

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
);

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
);

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.

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.

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
[C#]
public class SdtListItemCollection : IEnumerable

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;}

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;}

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;}

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
);

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();

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

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

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

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, DrawingML, SmartTag.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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.

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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.

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.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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 of Aspose.Words provides a number of public methods and properties to manipulate the behavior and content of StructuredDocumentTag. However databinding of SDT nodes to custom xml packages within a Document is not supported in this version of public API.

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.

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
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
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 readonly 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 DataBinding 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.
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.

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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:

  • DropDownList
  • ComboBox
  • Date
  • BuildingBlockGallery
  • Group
  • Picture
  • RichText
  • PlainText

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
ChildNodes (inherited from CompositeNode) | Gets all immediate child nodes of this node.
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 readonly 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 DataBinding 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.
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.

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 SDT type.

For all other SDT types exception will occur.

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 SDT type.

For all other SDT types exception will occur.

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.

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;}

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.

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.

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.

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;}

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.

See Also

StructuredDocumentTag Class | Aspose.Words.Markup Namespace


Id Property

Aspose.Words

StructuredDocumentTag.Id Property

Specifies a unique readonly 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 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.
  • DuringClone 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.

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;}

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;}

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;}

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.

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;}

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;}

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.

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;}

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 DataBinding 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.

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;}

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;}

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.

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;}

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.
Clone (inherited from Node) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

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();

See Also

StructuredDocumentTag 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.


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.

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.
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.
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.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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.
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.
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.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


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;}

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;}

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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.

See Also

OfficeMath Class | 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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty prop in doc.BuiltInDocumentProperties)
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);

Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty prop in doc.CustomDocumentProperties)
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For Each prop As DocumentProperty In doc.BuiltInDocumentProperties
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value)
Next prop

Console.WriteLine("3. Custom Properties")
For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value)
Next prop

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 DocumentPropertyCollection) | 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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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);
[Visual Basic]

Dim doc As 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)
Retrieves information from the built-in document properties.
[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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;}

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;}

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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.

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.

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 prop = doc.BuiltInDocumentProperties["Keywords"];
Console.WriteLine(prop.ToString());
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim prop As DocumentProperty = doc.BuiltInDocumentProperties("Keywords")
Console.WriteLine(prop.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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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 does not update this property.

Example

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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.

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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);
[Visual Basic]

Dim doc As 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)
Retrieves information from the built-in document properties.
[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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.

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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.

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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.

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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

Retrieves information from the built-in document properties.

[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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);
[Visual Basic]

Dim doc As 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)
Retrieves information from the built-in document properties.
[C#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("Document name: {0}", fileName);
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes);
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category);
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters);
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces);
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments);
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company);
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime);
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords);
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted);
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy);
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime);
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines);
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager);
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication);
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages);
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs);
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber);
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject);
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template);
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime);
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version);
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("Document name: {0}", fileName)
Console.WriteLine("Document author: {0}", doc.BuiltInDocumentProperties.Author)
Console.WriteLine("Bytes: {0}", doc.BuiltInDocumentProperties.Bytes)
Console.WriteLine("Category: {0}", doc.BuiltInDocumentProperties.Category)
Console.WriteLine("Characters: {0}", doc.BuiltInDocumentProperties.Characters)
Console.WriteLine("Characters with spaces: {0}", doc.BuiltInDocumentProperties.CharactersWithSpaces)
Console.WriteLine("Comments: {0}", doc.BuiltInDocumentProperties.Comments)
Console.WriteLine("Company: {0}", doc.BuiltInDocumentProperties.Company)
Console.WriteLine("Create time: {0}", doc.BuiltInDocumentProperties.CreatedTime)
Console.WriteLine("Keywords: {0}", doc.BuiltInDocumentProperties.Keywords)
Console.WriteLine("Last printed: {0}", doc.BuiltInDocumentProperties.LastPrinted)
Console.WriteLine("Last saved by: {0}", doc.BuiltInDocumentProperties.LastSavedBy)
Console.WriteLine("Last saved: {0}", doc.BuiltInDocumentProperties.LastSavedTime)
Console.WriteLine("Lines: {0}", doc.BuiltInDocumentProperties.Lines)
Console.WriteLine("Manager: {0}", doc.BuiltInDocumentProperties.Manager)
Console.WriteLine("Name of application: {0}", doc.BuiltInDocumentProperties.NameOfApplication)
Console.WriteLine("Pages: {0}", doc.BuiltInDocumentProperties.Pages)
Console.WriteLine("Paragraphs: {0}", doc.BuiltInDocumentProperties.Paragraphs)
Console.WriteLine("Revision number: {0}", doc.BuiltInDocumentProperties.RevisionNumber)
Console.WriteLine("Subject: {0}", doc.BuiltInDocumentProperties.Subject)
Console.WriteLine("Template: {0}", doc.BuiltInDocumentProperties.Template)
Console.WriteLine("Title: {0}", doc.BuiltInDocumentProperties.Title)
Console.WriteLine("Total editing time: {0}", doc.BuiltInDocumentProperties.TotalEditingTime)
Console.WriteLine("Version: {0}", doc.BuiltInDocumentProperties.Version)
Console.WriteLine("Words: {0}", doc.BuiltInDocumentProperties.Words)

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty prop in doc.BuiltInDocumentProperties)
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);

Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty prop in doc.CustomDocumentProperties)
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value);
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For Each prop As DocumentProperty In doc.BuiltInDocumentProperties
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value)
Next prop

Console.WriteLine("3. Custom Properties")
For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine("{0} : {1}", prop.Name, prop.Value)
Next prop

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 DocumentPropertyCollection) | 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 DocumentPropertyCollection) | 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

Checks if a custom property with a given name exists in a document and adds few more custom document properties.

[C#]

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

CustomDocumentProperties props = doc.CustomDocumentProperties;

if (props["Authorized"] == null)
{
    props.Add("Authorized", true);
    props.Add("Authorized By", "John Smith");
    props.Add("Authorized Date", DateTime.Today);
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
    props.Add("Authorized Amount", 123.45);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim props As CustomDocumentProperties = doc.CustomDocumentProperties

If props("Authorized") Is Nothing Then
    props.Add("Authorized", True)
    props.Add("Authorized By", "John Smith")
    props.Add("Authorized Date", DateTime.Today)
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber)
    props.Add("Authorized Amount", 123.45)
End If

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 prop = doc.CustomDocumentProperties["Authorized Date"];

if (prop != null)
{
    Console.WriteLine(prop.ToDateTime());
}
else
{
    Console.WriteLine("The document is not authorized. Authorizing...");
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim prop As DocumentProperty = doc.CustomDocumentProperties("Authorized Date")

If prop IsNot Nothing Then
    Console.WriteLine(prop.ToDateTime())
Else
    Console.WriteLine("The document is not authorized. Authorizing...")
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now)
End If
Checks if a custom property with a given name exists in a document and adds few more custom document properties.
[C#]

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

CustomDocumentProperties props = doc.CustomDocumentProperties;

if (props["Authorized"] == null)
{
    props.Add("Authorized", true);
    props.Add("Authorized By", "John Smith");
    props.Add("Authorized Date", DateTime.Today);
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
    props.Add("Authorized Amount", 123.45);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim props As CustomDocumentProperties = doc.CustomDocumentProperties

If props("Authorized") Is Nothing Then
    props.Add("Authorized", True)
    props.Add("Authorized By", "John Smith")
    props.Add("Authorized Date", DateTime.Today)
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber)
    props.Add("Authorized Amount", 123.45)
End If

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

Checks if a custom property with a given name exists in a document and adds few more custom document properties.

[C#]

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

CustomDocumentProperties props = doc.CustomDocumentProperties;

if (props["Authorized"] == null)
{
    props.Add("Authorized", true);
    props.Add("Authorized By", "John Smith");
    props.Add("Authorized Date", DateTime.Today);
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
    props.Add("Authorized Amount", 123.45);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim props As CustomDocumentProperties = doc.CustomDocumentProperties

If props("Authorized") Is Nothing Then
    props.Add("Authorized", True)
    props.Add("Authorized By", "John Smith")
    props.Add("Authorized Date", DateTime.Today)
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber)
    props.Add("Authorized Amount", 123.45)
End If

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

Checks if a custom property with a given name exists in a document and adds few more custom document properties.

[C#]

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

CustomDocumentProperties props = doc.CustomDocumentProperties;

if (props["Authorized"] == null)
{
    props.Add("Authorized", true);
    props.Add("Authorized By", "John Smith");
    props.Add("Authorized Date", DateTime.Today);
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
    props.Add("Authorized Amount", 123.45);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim props As CustomDocumentProperties = doc.CustomDocumentProperties

If props("Authorized") Is Nothing Then
    props.Add("Authorized", True)
    props.Add("Authorized By", "John Smith")
    props.Add("Authorized Date", DateTime.Today)
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber)
    props.Add("Authorized Amount", 123.45)
End If

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

Checks if a custom property with a given name exists in a document and adds few more custom document properties.

[C#]

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

CustomDocumentProperties props = doc.CustomDocumentProperties;

if (props["Authorized"] == null)
{
    props.Add("Authorized", true);
    props.Add("Authorized By", "John Smith");
    props.Add("Authorized Date", DateTime.Today);
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
    props.Add("Authorized Amount", 123.45);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim props As CustomDocumentProperties = doc.CustomDocumentProperties

If props("Authorized") Is Nothing Then
    props.Add("Authorized", True)
    props.Add("Authorized By", "John Smith")
    props.Add("Authorized Date", DateTime.Today)
    props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber)
    props.Add("Authorized Amount", 123.45)
End If

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For i As Integer = 0 To doc.BuiltInDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.BuiltInDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

Console.WriteLine("3. Custom Properties")
For i As Integer = 0 To doc.CustomDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.CustomDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For i As Integer = 0 To doc.BuiltInDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.BuiltInDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

Console.WriteLine("3. Custom Properties")
For i As Integer = 0 To doc.CustomDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.CustomDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For i As Integer = 0 To doc.BuiltInDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.BuiltInDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

Console.WriteLine("3. Custom Properties")
For i As Integer = 0 To doc.CustomDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.CustomDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i
Retrieves the types and values of the custom document properties.
[C#]

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

foreach (DocumentProperty prop in doc.CustomDocumentProperties)
{
    Console.WriteLine(prop.Name);
    switch (prop.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a string value.");
            Console.WriteLine(prop.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(prop.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(prop.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(prop.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(prop.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine(prop.Name)
    Select Case prop.Type
        Case PropertyType.String
            Console.WriteLine("It's a string value.")
            Console.WriteLine(prop.ToString())
        Case PropertyType.Boolean
            Console.WriteLine("It's a boolean value.")
            Console.WriteLine(prop.ToBool())
        Case PropertyType.Number
            Console.WriteLine("It's an integer value.")
            Console.WriteLine(prop.ToInt())
        Case PropertyType.DateTime
            Console.WriteLine("It's a date time value.")
            Console.WriteLine(prop.ToDateTime())
        Case PropertyType.Double
            Console.WriteLine("It's a double value.")
            Console.WriteLine(prop.ToDouble())
        Case PropertyType.Other
            Console.WriteLine("Other value.")
        Case Else
            Throw New Exception("Unknown property type.")
    End Select
Next prop

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For i As Integer = 0 To doc.BuiltInDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.BuiltInDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

Console.WriteLine("3. Custom Properties")
For i As Integer = 0 To doc.CustomDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.CustomDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

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 prop in doc.CustomDocumentProperties)
{
    Console.WriteLine(prop.Name);
    switch (prop.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a string value.");
            Console.WriteLine(prop.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(prop.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(prop.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(prop.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(prop.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine(prop.Name)
    Select Case prop.Type
        Case PropertyType.String
            Console.WriteLine("It's a string value.")
            Console.WriteLine(prop.ToString())
        Case PropertyType.Boolean
            Console.WriteLine("It's a boolean value.")
            Console.WriteLine(prop.ToBool())
        Case PropertyType.Number
            Console.WriteLine("It's an integer value.")
            Console.WriteLine(prop.ToInt())
        Case PropertyType.DateTime
            Console.WriteLine("It's a date time value.")
            Console.WriteLine(prop.ToDateTime())
        Case PropertyType.Double
            Console.WriteLine("It's a double value.")
            Console.WriteLine(prop.ToDouble())
        Case PropertyType.Other
            Console.WriteLine("Other value.")
        Case Else
            Throw New Exception("Unknown property type.")
    End Select
Next prop

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.

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 prop = doc.CustomDocumentProperties["Authorized Date"];

if (prop != null)
{
    Console.WriteLine(prop.ToDateTime());
}
else
{
    Console.WriteLine("The document is not authorized. Authorizing...");
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim prop As DocumentProperty = doc.CustomDocumentProperties("Authorized Date")

If prop IsNot Nothing Then
    Console.WriteLine(prop.ToDateTime())
Else
    Console.WriteLine("The document is not authorized. Authorizing...")
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now)
End If
Retrieves the types and values of the custom document properties.
[C#]

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

foreach (DocumentProperty prop in doc.CustomDocumentProperties)
{
    Console.WriteLine(prop.Name);
    switch (prop.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a string value.");
            Console.WriteLine(prop.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(prop.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(prop.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(prop.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(prop.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine(prop.Name)
    Select Case prop.Type
        Case PropertyType.String
            Console.WriteLine("It's a string value.")
            Console.WriteLine(prop.ToString())
        Case PropertyType.Boolean
            Console.WriteLine("It's a boolean value.")
            Console.WriteLine(prop.ToBool())
        Case PropertyType.Number
            Console.WriteLine("It's an integer value.")
            Console.WriteLine(prop.ToInt())
        Case PropertyType.DateTime
            Console.WriteLine("It's a date time value.")
            Console.WriteLine(prop.ToDateTime())
        Case PropertyType.Double
            Console.WriteLine("It's a double value.")
            Console.WriteLine(prop.ToDouble())
        Case PropertyType.Other
            Console.WriteLine("Other value.")
        Case Else
            Throw New Exception("Unknown property type.")
    End Select
Next prop

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 prop in doc.CustomDocumentProperties)
{
    Console.WriteLine(prop.Name);
    switch (prop.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a string value.");
            Console.WriteLine(prop.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(prop.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(prop.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(prop.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(prop.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine(prop.Name)
    Select Case prop.Type
        Case PropertyType.String
            Console.WriteLine("It's a string value.")
            Console.WriteLine(prop.ToString())
        Case PropertyType.Boolean
            Console.WriteLine("It's a boolean value.")
            Console.WriteLine(prop.ToBool())
        Case PropertyType.Number
            Console.WriteLine("It's an integer value.")
            Console.WriteLine(prop.ToInt())
        Case PropertyType.DateTime
            Console.WriteLine("It's a date time value.")
            Console.WriteLine(prop.ToDateTime())
        Case PropertyType.Double
            Console.WriteLine("It's a double value.")
            Console.WriteLine(prop.ToDouble())
        Case PropertyType.Other
            Console.WriteLine("Other value.")
        Case Else
            Throw New Exception("Unknown property type.")
    End Select
Next prop

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 prop in doc.CustomDocumentProperties)
{
    Console.WriteLine(prop.Name);
    switch (prop.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a string value.");
            Console.WriteLine(prop.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(prop.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(prop.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(prop.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(prop.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine(prop.Name)
    Select Case prop.Type
        Case PropertyType.String
            Console.WriteLine("It's a string value.")
            Console.WriteLine(prop.ToString())
        Case PropertyType.Boolean
            Console.WriteLine("It's a boolean value.")
            Console.WriteLine(prop.ToBool())
        Case PropertyType.Number
            Console.WriteLine("It's an integer value.")
            Console.WriteLine(prop.ToInt())
        Case PropertyType.DateTime
            Console.WriteLine("It's a date time value.")
            Console.WriteLine(prop.ToDateTime())
        Case PropertyType.Double
            Console.WriteLine("It's a double value.")
            Console.WriteLine(prop.ToDouble())
        Case PropertyType.Other
            Console.WriteLine("Other value.")
        Case Else
            Throw New Exception("Unknown property type.")
    End Select
Next prop

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 prop = doc.BuiltInDocumentProperties["Keywords"];
Console.WriteLine(prop.ToString());
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim prop As DocumentProperty = doc.BuiltInDocumentProperties("Keywords")
Console.WriteLine(prop.ToString())
Retrieves the types and values of the custom document properties.
[C#]

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

foreach (DocumentProperty prop in doc.CustomDocumentProperties)
{
    Console.WriteLine(prop.Name);
    switch (prop.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a string value.");
            Console.WriteLine(prop.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(prop.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(prop.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(prop.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(prop.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine(prop.Name)
    Select Case prop.Type
        Case PropertyType.String
            Console.WriteLine("It's a string value.")
            Console.WriteLine(prop.ToString())
        Case PropertyType.Boolean
            Console.WriteLine("It's a boolean value.")
            Console.WriteLine(prop.ToBool())
        Case PropertyType.Number
            Console.WriteLine("It's an integer value.")
            Console.WriteLine(prop.ToInt())
        Case PropertyType.DateTime
            Console.WriteLine("It's a date time value.")
            Console.WriteLine(prop.ToDateTime())
        Case PropertyType.Double
            Console.WriteLine("It's a double value.")
            Console.WriteLine(prop.ToDouble())
        Case PropertyType.Other
            Console.WriteLine("Other value.")
        Case Else
            Throw New Exception("Unknown property type.")
    End Select
Next prop

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
[C#]
public abstract class DocumentPropertyCollection : IEnumerable

Remarks

The names of the properties are case-insensitive.

The properties in the collection are sorted alphabetically by name.

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For i As Integer = 0 To doc.BuiltInDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.BuiltInDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

Console.WriteLine("3. Custom Properties")
For i As Integer = 0 To doc.CustomDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.CustomDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

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#]

string fileName = MyDir + "Properties.doc";
Document doc = new Document(fileName);

Console.WriteLine("1. Document name: {0}", fileName);

Console.WriteLine("2. Built-in Properties");
for (int i = 0; i < doc.BuiltInDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.BuiltInDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}

Console.WriteLine("3. Custom Properties");
for (int i = 0; i < doc.CustomDocumentProperties.Count; i++)
{
    DocumentProperty prop = doc.CustomDocumentProperties[i];
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value);
}
[Visual Basic]

Dim fileName As String = MyDir & "Properties.doc"
Dim doc As New Document(fileName)

Console.WriteLine("1. Document name: {0}", fileName)

Console.WriteLine("2. Built-in Properties")
For i As Integer = 0 To doc.BuiltInDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.BuiltInDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

Console.WriteLine("3. Custom Properties")
For i As Integer = 0 To doc.CustomDocumentProperties.Count - 1
    Dim prop As DocumentProperty = doc.CustomDocumentProperties(i)
    Console.WriteLine("{0}({1}) : {2}", prop.Name, prop.Type, prop.Value)
Next i

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 prop = doc.CustomDocumentProperties["Authorized Date"];

if (prop != null)
{
    Console.WriteLine(prop.ToDateTime());
}
else
{
    Console.WriteLine("The document is not authorized. Authorizing...");
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

Dim prop As DocumentProperty = doc.CustomDocumentProperties("Authorized Date")

If prop IsNot Nothing Then
    Console.WriteLine(prop.ToDateTime())
Else
    Console.WriteLine("The document is not authorized. Authorizing...")
    doc.CustomDocumentProperties.Add("AuthorizedDate", DateTime.Now)
End If

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();

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.

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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

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.

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

Removes a custom document property.

[C#]

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

doc.CustomDocumentProperties.Remove("Authorized Date");
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

doc.CustomDocumentProperties.Remove("Authorized Date")

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.

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.

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

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 prop in doc.CustomDocumentProperties)
{
    Console.WriteLine(prop.Name);
    switch (prop.Type)
    {
        case PropertyType.String:
            Console.WriteLine("It's a string value.");
            Console.WriteLine(prop.ToString());
            break;
        case PropertyType.Boolean:
            Console.WriteLine("It's a boolean value.");
            Console.WriteLine(prop.ToBool());
            break;
        case PropertyType.Number:
            Console.WriteLine("It's an integer value.");
            Console.WriteLine(prop.ToInt());
            break;
        case PropertyType.DateTime:
            Console.WriteLine("It's a date time value.");
            Console.WriteLine(prop.ToDateTime());
            break;
        case PropertyType.Double:
            Console.WriteLine("It's a double value.");
            Console.WriteLine(prop.ToDouble());
            break;
        case PropertyType.Other:
            Console.WriteLine("Other value.");
            break;
        default:
            throw new Exception("Unknown property type.");
    }
}
[Visual Basic]

Dim doc As New Document(MyDir & "Properties.doc")

For Each prop As DocumentProperty In doc.CustomDocumentProperties
    Console.WriteLine(prop.Name)
    Select Case prop.Type
        Case PropertyType.String
            Console.WriteLine("It's a string value.")
            Console.WriteLine(prop.ToString())
        Case PropertyType.Boolean
            Console.WriteLine("It's a boolean value.")
            Console.WriteLine(prop.ToBool())
        Case PropertyType.Number
            Console.WriteLine("It's an integer value.")
            Console.WriteLine(prop.ToInt())
        Case PropertyType.DateTime
            Console.WriteLine("It's a date time value.")
            Console.WriteLine(prop.ToDateTime())
        Case PropertyType.Double
            Console.WriteLine("It's a double value.")
            Console.WriteLine(prop.ToDouble())
        Case PropertyType.Other
            Console.WriteLine("Other value.")
        Case Else
            Throw New Exception("Unknown property type.")
    End Select
Next prop

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.
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.
AsposeWordsPrintDocument awPrintDoc = new AsposeWordsPrintDocument(doc);
awPrintDoc.PrinterSettings = printDlg.PrinterSettings;

// 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();
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim previewDlg As 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.
Dim printDlg As New PrintDialog()
printDlg.AllowSomePages = True
printDlg.PrinterSettings.MinimumPage = 1
printDlg.PrinterSettings.MaximumPage = doc.PageCount
printDlg.PrinterSettings.FromPage = 1
printDlg.PrinterSettings.ToPage = doc.PageCount

If (Not printDlg.ShowDialog().Equals(DialogResult.OK)) Then
    Return
End If

' Create the Aspose.Words' implementation of the .NET print document
' and pass the printer settings from the dialog to the print document.
Dim awPrintDoc As New AsposeWordsPrintDocument(doc)
awPrintDoc.PrinterSettings = printDlg.PrinterSettings

' 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.

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


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);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Console.WriteLine("Document ""{0}"" contains {1} pages.", doc.OriginalFileName, doc.PageCount)

For i As Integer = 0 To doc.PageCount - 1
    Dim pageInfo As 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,If(pageInfo.Landscape, "Landscape", "Portrait"), pageInfo.PaperTray)
Next i
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);

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(MyDir + "Rendering.RenderToScale Out.png");
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim pageInfo As PageInfo = doc.GetPageInfo(0)

' Let's say we want the image at 50% zoom.
Const MyScale As Single = 0.50f

' Let's say we want the image at this resolution.
Const MyResolution As Single = 200.0f

Dim pageSize As Size = pageInfo.GetSizeInPixels(MyScale, MyResolution)

Using img As New Bitmap(pageSize.Width, pageSize.Height)
    img.SetResolution(MyResolution, MyResolution)

    Using gr As Graphics = 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)
    End Using

    img.Save(MyDir & "Rendering.RenderToScale Out.png")
End Using

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 | 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);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Console.WriteLine("Document ""{0}"" contains {1} pages.", doc.OriginalFileName, doc.PageCount)

For i As Integer = 0 To doc.PageCount - 1
    Dim pageInfo As 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,If(pageInfo.Landscape, "Landscape", "Portrait"), pageInfo.PaperTray)
Next i

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);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Console.WriteLine("Document ""{0}"" contains {1} pages.", doc.OriginalFileName, doc.PageCount)

For i As Integer = 0 To doc.PageCount - 1
    Dim pageInfo As 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,If(pageInfo.Landscape, "Landscape", "Portrait"), pageInfo.PaperTray)
Next i
Shows how to implement your own .NET PrintDocument to completely customize printing of Aspose.Words documents.
[C#]

public void CustomPrint()
        {
            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;
        }
[Visual Basic]

<Test, Explicit> _
        Public Sub CustomPrint()
            Dim doc As New Document(MyDir & "Rendering.doc")

            ' Create an instance of our own PrintDocument.
            Dim printDoc As 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()
        End Sub

        ''' <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
            Inherits PrintDocument
            Public Sub New(ByVal document As Document)
                mDocument = document
            End Sub

            ''' <summary>
            ''' Called before the printing starts.
            ''' </summary>
            Protected Overrides Sub OnBeginPrint(ByVal e As PrintEventArgs)
                MyBase.OnBeginPrint(e)

                ' Initialize the range of pages to be printed according to the user selection.
                Select Case PrinterSettings.PrintRange
                    Case System.Drawing.Printing.PrintRange.AllPages
                        mCurrentPage = 1
                        mPageTo = mDocument.PageCount
                    Case System.Drawing.Printing.PrintRange.SomePages
                        mCurrentPage = PrinterSettings.FromPage
                        mPageTo = PrinterSettings.ToPage
                    Case Else
                        Throw New InvalidOperationException("Unsupported print range.")
                End Select
            End Sub

            ''' <summary>
            ''' Called before each page is printed.
            ''' </summary>
            Protected Overrides Sub OnQueryPageSettings(ByVal e As QueryPageSettingsEventArgs)
                MyBase.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.
                Dim pageInfo As 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
            End Sub

            ''' <summary>
            ''' Called for each page to render it for printing.
            ''' </summary>
            Protected Overrides Sub OnPrintPage(ByVal e As PrintPageEventArgs)
                MyBase.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.
                Dim hardOffsetX As Single = 20
                Dim hardOffsetY As Single = 20

                ' This is in .NET 2.0 only. Uncomment when needed.
'                float hardOffsetX = e.PageSettings.HardMarginX;
'                float hardOffsetY = e.PageSettings.HardMarginY;

                Dim pageIndex As Integer = mCurrentPage - 1
                mDocument.RenderToScale(mCurrentPage, e.Graphics, -hardOffsetX, -hardOffsetY, 1.0f)

                mCurrentPage += 1
                e.HasMorePages = (mCurrentPage <= mPageTo)
            End Sub

            Private ReadOnly mDocument As Document
            Private mCurrentPage As Integer
            Private mPageTo As Integer
        End Class

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);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Console.WriteLine("Document ""{0}"" contains {1} pages.", doc.OriginalFileName, doc.PageCount)

For i As Integer = 0 To doc.PageCount - 1
    Dim pageInfo As 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,If(pageInfo.Landscape, "Landscape", "Portrait"), pageInfo.PaperTray)
Next i

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);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Console.WriteLine("Document ""{0}"" contains {1} pages.", doc.OriginalFileName, doc.PageCount)

For i As Integer = 0 To doc.PageCount - 1
    Dim pageInfo As 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,If(pageInfo.Landscape, "Landscape", "Portrait"), pageInfo.PaperTray)
Next i

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);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Console.WriteLine("Document ""{0}"" contains {1} pages.", doc.OriginalFileName, doc.PageCount)

For i As Integer = 0 To doc.PageCount - 1
    Dim pageInfo As 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,If(pageInfo.Landscape, "Landscape", "Portrait"), pageInfo.PaperTray)
Next i

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 | 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#]

public void CustomPrint()
        {
            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;
        }
[Visual Basic]

<Test, Explicit> _
        Public Sub CustomPrint()
            Dim doc As New Document(MyDir & "Rendering.doc")

            ' Create an instance of our own PrintDocument.
            Dim printDoc As 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()
        End Sub

        ''' <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
            Inherits PrintDocument
            Public Sub New(ByVal document As Document)
                mDocument = document
            End Sub

            ''' <summary>
            ''' Called before the printing starts.
            ''' </summary>
            Protected Overrides Sub OnBeginPrint(ByVal e As PrintEventArgs)
                MyBase.OnBeginPrint(e)

                ' Initialize the range of pages to be printed according to the user selection.
                Select Case PrinterSettings.PrintRange
                    Case System.Drawing.Printing.PrintRange.AllPages
                        mCurrentPage = 1
                        mPageTo = mDocument.PageCount
                    Case System.Drawing.Printing.PrintRange.SomePages
                        mCurrentPage = PrinterSettings.FromPage
                        mPageTo = PrinterSettings.ToPage
                    Case Else
                        Throw New InvalidOperationException("Unsupported print range.")
                End Select
            End Sub

            ''' <summary>
            ''' Called before each page is printed.
            ''' </summary>
            Protected Overrides Sub OnQueryPageSettings(ByVal e As QueryPageSettingsEventArgs)
                MyBase.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.
                Dim pageInfo As 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
            End Sub

            ''' <summary>
            ''' Called for each page to render it for printing.
            ''' </summary>
            Protected Overrides Sub OnPrintPage(ByVal e As PrintPageEventArgs)
                MyBase.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.
                Dim hardOffsetX As Single = 20
                Dim hardOffsetY As Single = 20

                ' This is in .NET 2.0 only. Uncomment when needed.
'                float hardOffsetX = e.PageSettings.HardMarginX;
'                float hardOffsetY = e.PageSettings.HardMarginY;

                Dim pageIndex As Integer = mCurrentPage - 1
                mDocument.RenderToScale(mCurrentPage, e.Graphics, -hardOffsetX, -hardOffsetY, 1.0f)

                mCurrentPage += 1
                e.HasMorePages = (mCurrentPage <= mPageTo)
            End Sub

            Private ReadOnly mDocument As Document
            Private mCurrentPage As Integer
            Private mPageTo As Integer
        End Class

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


PageInfo.GetSizeInPixels Method

Calculates the page size in pixels for a specified zoom factor and resolution.

[Visual Basic]
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 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);

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(MyDir + "Rendering.RenderToScale Out.png");
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim pageInfo As PageInfo = doc.GetPageInfo(0)

' Let's say we want the image at 50% zoom.
Const MyScale As Single = 0.50f

' Let's say we want the image at this resolution.
Const MyResolution As Single = 200.0f

Dim pageSize As Size = pageInfo.GetSizeInPixels(MyScale, MyResolution)

Using img As New Bitmap(pageSize.Width, pageSize.Height)
    img.SetResolution(MyResolution, MyResolution)

    Using gr As Graphics = 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)
    End Using

    img.Save(MyDir & "Rendering.RenderToScale Out.png")
End Using

See Also

PageInfo Class | Aspose.Words.Rendering Namespace


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.ShapeRenderer

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

Example

Shows how to render a shape independent of the document to an EMF image and save it to disk.

[C#]

// The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Emf)
{
    Scale = 1.5f
};

// Save the rendered image to disk.
r.Save(dataDir + "TestFile.RenderToDisk Out.emf", imageOptions);
[Visual Basic]

' The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Emf) With {.Scale = 1.5f}

' Save the rendered image to disk.
r.Save(dataDir & "TestFile.RenderToDisk Out.emf", imageOptions)
Shows how to render a shape independent of the document to a JPEG image and save it to a stream.
[C#]

// We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
ShapeRenderer r = new ShapeRenderer(shape);

// Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg)
{
    // Output the image in gray scale
    ImageColorMode = ImageColorMode.Grayscale,

    // Reduce the brightness a bit (default is 0.5f).
    ImageBrightness = 0.45f
};

FileStream stream = new FileStream(dataDir + "TestFile.RenderToStream Out.jpg", FileMode.CreateNew);

// Save the rendered image to the stream using different options.
r.Save(stream, imageOptions);
[Visual Basic]

' We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
Dim r As New ShapeRenderer(shape)

' Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
    ' Output the image in gray scale
    ' Reduce the brightness a bit (default is 0.5f).
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg) With {.ImageColorMode = ImageColorMode.Grayscale, .ImageBrightness = 0.45f}

Dim stream As New FileStream(dataDir & "TestFile.RenderToStream Out.jpg", FileMode.CreateNew)

' Save the rendered image to the stream using different options.
r.Save(stream, imageOptions)
Shows how to render a shape independent of the document to a .NET Graphics object and apply rotation to the rendered image.
[C#]

// The shape renderer is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Find the size that the shape will be rendered to at the specified scale and resolution.
Size shapeSizeInPixels = r.GetSizeInPixels(1.0f, 96.0f);

// Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
// and make sure that the graphics canvas is large enough to compensate for this.
int maxSide = Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height);

using (Bitmap image = new Bitmap((int)(maxSide * 1.25), (int)(maxSide * 1.25)))
{
    // Rendering to a graphics object means we can specify settings and transformations to be applied to
    // the shape that is rendered. In our case we will rotate the rendered shape.
    using (Graphics gr = Graphics.FromImage(image))
    {
        // Clear the shape with the background color of the document.
        gr.Clear(Color.White);
        // Center the rotation using translation method below
        gr.TranslateTransform((float)image.Width / 8, (float)image.Height / 2);
        // Rotate the image by 45 degrees.
        gr.RotateTransform(45);
        // Undo the translation.
        gr.TranslateTransform(-(float)image.Width / 8, -(float)image.Height / 2);

        // Render the shape onto the graphics object.
        r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height);
    }

    image.Save(dataDir + "TestFile.RenderToGraphics.png", ImageFormat.Png);
}
[Visual Basic]

' The shape renderer is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Find the size that the shape will be rendered to at the specified scale and resolution.
Dim shapeSizeInPixels As Size = r.GetSizeInPixels(1.0f, 96.0f)

' Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
' and make sure that the graphics canvas is large enough to compensate for this.
Dim maxSide As Integer = Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height)

Using image As New Bitmap(CInt(Fix(maxSide * 1.25)), CInt(Fix(maxSide * 1.25)))
    ' Rendering to a graphics object means we can specify settings and transformations to be applied to
    ' the shape that is rendered. In our case we will rotate the rendered shape.
    Using gr As Graphics = Graphics.FromImage(image)
        ' Clear the shape with the background color of the document.
        gr.Clear(Color.White)
        ' Center the rotation using translation method below
        gr.TranslateTransform(CSng(image.Width) / 8, CSng(image.Height) / 2)
        ' Rotate the image by 45 degrees.
        gr.RotateTransform(45)
        ' Undo the translation.
        gr.TranslateTransform(-CSng(image.Width) / 8, -CSng(image.Height) / 2)

        ' Render the shape onto the graphics object.
        r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height)
    End Using

    image.Save(dataDir & "TestFile.RenderToGraphics.png", ImageFormat.Png)
End Using

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 Overloaded. Initializes a new instance of the ShapeRenderer class.

Public Instance Properties

SizeInPoints Gets the actual size of the shape in points.

Public Instance Methods

GetSizeInPixels | 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

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ShapeRenderer Constructor

Initializes a new instance of this class.

Overload List

Initializes a new instance of this class.

public ShapeRenderer(DrawingML);

Initializes a new instance of this class.

public ShapeRenderer(ShapeBase);

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ShapeRenderer Constructor (DrawingML)

Initializes a new instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal shape As DrawingML _
)
[C#]
public ShapeRenderer(
DrawingML shape
);

Parameters

shape
The DrawinML shape object that you want to render.

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace | ShapeRenderer Constructor Overload List


ShapeRenderer Constructor (ShapeBase)

Initializes a new instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal shape As ShapeBase _
)
[C#]
public ShapeRenderer(
ShapeBase shape
);

Parameters

shape
The shape object that you want to render.

Example

Shows how to render a shape independent of the document to a JPEG image and save it to a stream.

[C#]

// We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
ShapeRenderer r = new ShapeRenderer(shape);

// Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg)
{
    // Output the image in gray scale
    ImageColorMode = ImageColorMode.Grayscale,

    // Reduce the brightness a bit (default is 0.5f).
    ImageBrightness = 0.45f
};

FileStream stream = new FileStream(dataDir + "TestFile.RenderToStream Out.jpg", FileMode.CreateNew);

// Save the rendered image to the stream using different options.
r.Save(stream, imageOptions);
[Visual Basic]

' We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
Dim r As New ShapeRenderer(shape)

' Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
    ' Output the image in gray scale
    ' Reduce the brightness a bit (default is 0.5f).
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg) With {.ImageColorMode = ImageColorMode.Grayscale, .ImageBrightness = 0.45f}

Dim stream As New FileStream(dataDir & "TestFile.RenderToStream Out.jpg", FileMode.CreateNew)

' Save the rendered image to the stream using different options.
r.Save(stream, imageOptions)

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace | ShapeRenderer Constructor Overload List


ShapeRenderer Properties

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

Public Instance Properties

SizeInPoints Gets the actual size of the shape in points.

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace


SizeInPoints Property

Aspose.Words

ShapeRenderer.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).

Example

Demonstrates how to find the size of a shape in the document and the size of the shape when rendered.

[C#]

SizeF shapeSizeInDocument = shape.GetShapeRenderer().SizeInPoints;
float width = shapeSizeInDocument.Width; // The width of the shape.
float height = shapeSizeInDocument.Height; // The height of the shape.
[Visual Basic]

Dim shapeSizeInDocument As SizeF = shape.GetShapeRenderer().SizeInPoints
Dim width As Single = shapeSizeInDocument.Width ' The width of the shape.
Dim height As Single = shapeSizeInDocument.Height ' The height of the shape.

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ShapeRenderer Methods

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

Public Instance Methods

GetSizeInPixels | 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

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ShapeRenderer.GetSizeInPixels Method

Calculates the size of the shape in pixels for a specified zoom factor and resolution.

[Visual Basic]
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 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.

Example

Shows how to create a new Bitmap and Graphics object with the width and height of the shape to be rendered.

[C#]

// We will render the shape at normal size and 96dpi. Calculate the size in pixels that the shape will be rendered at.
Size shapeRenderedSize = shape.GetShapeRenderer().GetSizeInPixels(1.0f, 96.0f);

using (Bitmap image = new Bitmap(shapeRenderedSize.Width, shapeRenderedSize.Height))
{
    using (Graphics g = Graphics.FromImage(image))
    {
        // Render shape onto the graphics object using the RenderToScale or RenderToSize methods of ShapeRenderer class.
    }
}
[Visual Basic]

' We will render the shape at normal size and 96dpi. Calculate the size in pixels that the shape will be rendered at.
Dim shapeRenderedSize As Size = shape.GetShapeRenderer().GetSizeInPixels(1.0f, 96.0f)

Using image As New Bitmap(shapeRenderedSize.Width, shapeRenderedSize.Height)
    Using g As Graphics = Graphics.FromImage(image)
        ' Render shape onto the graphics object using the RenderToScale or RenderToSize methods of ShapeRenderer class.
    End Using
End Using
Shows how to render a shape independent of the document to a .NET Graphics object and apply rotation to the rendered image.
[C#]

// The shape renderer is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Find the size that the shape will be rendered to at the specified scale and resolution.
Size shapeSizeInPixels = r.GetSizeInPixels(1.0f, 96.0f);

// Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
// and make sure that the graphics canvas is large enough to compensate for this.
int maxSide = Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height);

using (Bitmap image = new Bitmap((int)(maxSide * 1.25), (int)(maxSide * 1.25)))
{
    // Rendering to a graphics object means we can specify settings and transformations to be applied to
    // the shape that is rendered. In our case we will rotate the rendered shape.
    using (Graphics gr = Graphics.FromImage(image))
    {
        // Clear the shape with the background color of the document.
        gr.Clear(Color.White);
        // Center the rotation using translation method below
        gr.TranslateTransform((float)image.Width / 8, (float)image.Height / 2);
        // Rotate the image by 45 degrees.
        gr.RotateTransform(45);
        // Undo the translation.
        gr.TranslateTransform(-(float)image.Width / 8, -(float)image.Height / 2);

        // Render the shape onto the graphics object.
        r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height);
    }

    image.Save(dataDir + "TestFile.RenderToGraphics.png", ImageFormat.Png);
}
[Visual Basic]

' The shape renderer is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Find the size that the shape will be rendered to at the specified scale and resolution.
Dim shapeSizeInPixels As Size = r.GetSizeInPixels(1.0f, 96.0f)

' Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
' and make sure that the graphics canvas is large enough to compensate for this.
Dim maxSide As Integer = Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height)

Using image As New Bitmap(CInt(Fix(maxSide * 1.25)), CInt(Fix(maxSide * 1.25)))
    ' Rendering to a graphics object means we can specify settings and transformations to be applied to
    ' the shape that is rendered. In our case we will rotate the rendered shape.
    Using gr As Graphics = Graphics.FromImage(image)
        ' Clear the shape with the background color of the document.
        gr.Clear(Color.White)
        ' Center the rotation using translation method below
        gr.TranslateTransform(CSng(image.Width) / 8, CSng(image.Height) / 2)
        ' Rotate the image by 45 degrees.
        gr.RotateTransform(45)
        ' Undo the translation.
        gr.TranslateTransform(-CSng(image.Width) / 8, -CSng(image.Height) / 2)

        ' Render the shape onto the graphics object.
        r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height)
    End Using

    image.Save(dataDir & "TestFile.RenderToGraphics.png", ImageFormat.Png)
End Using

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ShapeRenderer.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

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ShapeRenderer.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.

Example

Shows how to render a shape independent of the document to a .NET Graphics object and apply rotation to the rendered image.

[C#]

// The shape renderer is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Find the size that the shape will be rendered to at the specified scale and resolution.
Size shapeSizeInPixels = r.GetSizeInPixels(1.0f, 96.0f);

// Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
// and make sure that the graphics canvas is large enough to compensate for this.
int maxSide = Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height);

using (Bitmap image = new Bitmap((int)(maxSide * 1.25), (int)(maxSide * 1.25)))
{
    // Rendering to a graphics object means we can specify settings and transformations to be applied to
    // the shape that is rendered. In our case we will rotate the rendered shape.
    using (Graphics gr = Graphics.FromImage(image))
    {
        // Clear the shape with the background color of the document.
        gr.Clear(Color.White);
        // Center the rotation using translation method below
        gr.TranslateTransform((float)image.Width / 8, (float)image.Height / 2);
        // Rotate the image by 45 degrees.
        gr.RotateTransform(45);
        // Undo the translation.
        gr.TranslateTransform(-(float)image.Width / 8, -(float)image.Height / 2);

        // Render the shape onto the graphics object.
        r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height);
    }

    image.Save(dataDir + "TestFile.RenderToGraphics.png", ImageFormat.Png);
}
[Visual Basic]

' The shape renderer is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Find the size that the shape will be rendered to at the specified scale and resolution.
Dim shapeSizeInPixels As Size = r.GetSizeInPixels(1.0f, 96.0f)

' Rotating the shape may result in clipping as the image canvas is too small. Find the longest side
' and make sure that the graphics canvas is large enough to compensate for this.
Dim maxSide As Integer = Math.Max(shapeSizeInPixels.Width, shapeSizeInPixels.Height)

Using image As New Bitmap(CInt(Fix(maxSide * 1.25)), CInt(Fix(maxSide * 1.25)))
    ' Rendering to a graphics object means we can specify settings and transformations to be applied to
    ' the shape that is rendered. In our case we will rotate the rendered shape.
    Using gr As Graphics = Graphics.FromImage(image)
        ' Clear the shape with the background color of the document.
        gr.Clear(Color.White)
        ' Center the rotation using translation method below
        gr.TranslateTransform(CSng(image.Width) / 8, CSng(image.Height) / 2)
        ' Rotate the image by 45 degrees.
        gr.RotateTransform(45)
        ' Undo the translation.
        gr.TranslateTransform(-CSng(image.Width) / 8, -CSng(image.Height) / 2)

        ' Render the shape onto the graphics object.
        r.RenderToSize(gr, 0, 0, shapeSizeInPixels.Width, shapeSizeInPixels.Height)
    End Using

    image.Save(dataDir & "TestFile.RenderToGraphics.png", ImageFormat.Png)
End Using

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace


Save Method

Aspose.Words

ShapeRenderer.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

ShapeRenderer Class | Aspose.Words.Rendering Namespace


ShapeRenderer.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.

Example

Shows how to render a shape independent of the document to a JPEG image and save it to a stream.

[C#]

// We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
ShapeRenderer r = new ShapeRenderer(shape);

// Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg)
{
    // Output the image in gray scale
    ImageColorMode = ImageColorMode.Grayscale,

    // Reduce the brightness a bit (default is 0.5f).
    ImageBrightness = 0.45f
};

FileStream stream = new FileStream(dataDir + "TestFile.RenderToStream Out.jpg", FileMode.CreateNew);

// Save the rendered image to the stream using different options.
r.Save(stream, imageOptions);
[Visual Basic]

' We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
Dim r As New ShapeRenderer(shape)

' Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
    ' Output the image in gray scale
    ' Reduce the brightness a bit (default is 0.5f).
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg) With {.ImageColorMode = ImageColorMode.Grayscale, .ImageBrightness = 0.45f}

Dim stream As New FileStream(dataDir & "TestFile.RenderToStream Out.jpg", FileMode.CreateNew)

' Save the rendered image to the stream using different options.
r.Save(stream, imageOptions)

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace | ShapeRenderer.Save Overload List


ShapeRenderer.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 render a DrawingML image independent of the document to a JPEG image on the disk.

[C#]

// Save the DrawingML image to disk in JPEG format and using default options.
drawingML.GetShapeRenderer().Save(dataDir + "TestFile.RenderDrawingML Out.jpg", null);
[Visual Basic]

' Save the DrawingML image to disk in JPEG format and using default options.
drawingML.GetShapeRenderer().Save(dataDir & "TestFile.RenderDrawingML Out.jpg", Nothing)
Shows how to render a shape independent of the document to an EMF image and save it to disk.
[C#]

// The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Emf)
{
    Scale = 1.5f
};

// Save the rendered image to disk.
r.Save(dataDir + "TestFile.RenderToDisk Out.emf", imageOptions);
[Visual Basic]

' The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Emf) With {.Scale = 1.5f}

' Save the rendered image to disk.
r.Save(dataDir & "TestFile.RenderToDisk Out.emf", imageOptions)

See Also

ShapeRenderer Class | Aspose.Words.Rendering Namespace | ShapeRenderer.Save Overload List


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.Reporting

Aspose.Words

Aspose.Words.Reporting Namespace

The Aspose.Words.Reporting namespace contains classes that form the reporting engine of Aspose.Words. The reporting engine allows to quickly and easily populate documents designed in Microsoft Word with data from various data 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.

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.
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.
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.Reporting.FieldMergingArgsBase
Aspose.Words.Reporting.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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

FieldMergingArgs Members | Aspose.Words.Reporting 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.Reporting 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.Reporting 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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

See Also

FieldMergingArgs Class | Aspose.Words.Reporting 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.Reporting.FieldMergingArgsBase
Aspose.Words.Reporting.FieldMergingArgs
Aspose.Words.Reporting.ImageFieldMergingArgs

[Visual Basic]
MustInherit Public Class FieldMergingArgsBase
[C#]
public abstract class FieldMergingArgsBase

Remarks

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

FieldMergingArgsBase Members | Aspose.Words.Reporting 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.Reporting 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.Reporting 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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

See Also

FieldMergingArgsBase Class | Aspose.Words.Reporting 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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

See Also

FieldMergingArgsBase Class | Aspose.Words.Reporting Namespace


Field Property

Aspose.Words

FieldMergingArgsBase.Field Property

Gets the object that represents the current merge field.

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

See Also

FieldMergingArgsBase Class | Aspose.Words.Reporting 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>>.
public void MailMergeInsertCheckBox()
{
    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(MyDir + "MailMerge.InsertCheckBox Out.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 e)
    {
        if (e.DocumentFieldName.Equals("CourseName"))
        {
            // Insert the checkbox for this merge field, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.FieldName);
            builder.InsertCheckBox(e.DocumentFieldName + mCheckBoxCount.ToString(), false, 0);
            builder.Write((string)e.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.ToString();
    }
    return dataTable;
}
[Visual Basic]

' File 'MailMerge.InsertCheckBox.doc' is a template
' containing the table with the following fields in it:
' <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
Public Sub MailMergeInsertCheckBox()
    Dim doc As New Document(MyDir & "MailMerge.InsertCheckBox.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertCheckBox()

    ' Execute mail merge with regions.
    Dim dataTable As DataTable = GetStudentCourseDataTable()
    doc.MailMerge.ExecuteWithRegions(dataTable)

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertCheckBox Out.doc")
End Sub

Private Class HandleMergeFieldInsertCheckBox
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called for each merge field in the document
    ''' when Document.MailMerge.ExecuteWithRegions is called.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        If e.DocumentFieldName.Equals("CourseName") Then
            ' Insert the checkbox for this merge field, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.FieldName)
            builder.InsertCheckBox(e.DocumentFieldName + mCheckBoxCount.ToString(), False, 0)
            builder.Write(CStr(e.FieldValue))
            mCheckBoxCount += 1
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub

    ''' <summary>
    ''' Counter for CheckBox name generation
    ''' </summary>
    Private mCheckBoxCount As Integer
End Class

''' <summary>
''' Create DataTable and fill it with data.
''' In real life this DataTable should be filled from a database.
''' </summary>
Private Shared Function GetStudentCourseDataTable() As DataTable
    Dim dataTable As New DataTable("StudentCourse")
    dataTable.Columns.Add("CourseName")
    For i As Integer = 0 To 9
        Dim datarow As DataRow = dataTable.NewRow()
        dataTable.Rows.Add(datarow)
        datarow(0) = "Course " & i.ToString()
    Next i
    Return dataTable
End Function

See Also

FieldMergingArgsBase Class | Aspose.Words.Reporting 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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

See Also

FieldMergingArgsBase Class | Aspose.Words.Reporting 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;}

See Also

FieldMergingArgsBase Class | Aspose.Words.Reporting 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 define custom logic in a handler implementing IFieldMergingCallback that is executed for unmerged regions in the document.

[C#]

public class EmptyRegionsHandler : IFieldMergingCallback
{
    /// <summary>
    /// Called for each field belonging to an unmerged region in the document.
    /// </summary>
    public void FieldMerging(FieldMergingArgs args)
    {
        // Change the text of each field of the ContactDetails region individually.
        if (args.TableName == "ContactDetails")
        {
            // Set the text of the field based off the field name.
            if (args.FieldName == "Name")
                args.Text = "(No details found)";
            else if (args.FieldName == "Number")
                args.Text = "(N/A)";
        }

        // Remove the entire table of the Suppliers region. Also check if the previous paragraph
        // before the table is a heading paragraph and if so remove that too.
        if (args.TableName == "Suppliers")
        {
            Table table = (Table)args.Field.Start.GetAncestor(NodeType.Table);

            // Check if the table has been removed from the document already.
            if (table.ParentNode != null)
            {
                // Try to find the paragraph which precedes the table before the table is removed from the document.
                if (table.PreviousSibling != null && table.PreviousSibling.NodeType == NodeType.Paragraph)
                {
                    Paragraph previousPara = (Paragraph)table.PreviousSibling;
                    if (IsHeadingParagraph(previousPara))
                        previousPara.Remove();
                }

                table.Remove();
            }
        }
    }

    /// <summary>
    /// Returns true if the paragraph uses any Heading style e.g Heading 1 to Heading 9
    /// </summary>
    private bool IsHeadingParagraph(Paragraph para)
    {
        return (para.ParagraphFormat.StyleIdentifier >= StyleIdentifier.Heading1 && para.ParagraphFormat.StyleIdentifier <= StyleIdentifier.Heading9);
    }

    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        // Do Nothing
    }
}
[Visual Basic]

Public Class EmptyRegionsHandler
    Implements IFieldMergingCallback
    ''' <summary>
    ''' Called for each field belonging to an unmerged region in the document.
    ''' </summary>
    Public Sub FieldMerging(ByVal args As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' Change the text of each field of the ContactDetails region individually.
        If args.TableName = "ContactDetails" Then
            ' Set the text of the field based off the field name.
            If args.FieldName = "Name" Then
                args.Text = "(No details found)"
            ElseIf args.FieldName = "Number" Then
                args.Text = "(N/A)"
            End If
        End If

        ' Remove the entire table of the Suppliers region. Also check if the previous paragraph
        ' before the table is a heading paragraph and if so remove that too.
        If args.TableName = "Suppliers" Then
            Dim table As Table = CType(args.Field.Start.GetAncestor(NodeType.Table), Table)

            ' Check if the table has been removed from the document already.
            If table.ParentNode IsNot Nothing Then
                ' Try to find the paragraph which precedes the table before the table is removed from the document.
                If table.PreviousSibling IsNot Nothing AndAlso table.PreviousSibling.NodeType = NodeType.Paragraph Then
                    Dim previousPara As Paragraph = CType(table.PreviousSibling, Paragraph)
                    If IsHeadingParagraph(previousPara) Then
                        previousPara.Remove()
                    End If
                End If

                table.Remove()
            End If
        End If
    End Sub

    ''' <summary>
    ''' Returns true if the paragraph uses any Heading style e.g Heading 1 to Heading 9
    ''' </summary>
    Private Function IsHeadingParagraph(ByVal para As Paragraph) As Boolean
        Return (para.ParagraphFormat.StyleIdentifier >= StyleIdentifier.Heading1 AndAlso para.ParagraphFormat.StyleIdentifier <= StyleIdentifier.Heading9)
    End Function

    Public Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do Nothing
    End Sub
End Class

See Also

FieldMergingArgsBase Class | Aspose.Words.Reporting 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#]

public void MailMergeImageFromBlob()
{
    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.Jet.OLEDB.4.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(MyDir + "MailMerge.MergeImage Out.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;
    }
}
[Visual Basic]

Public Sub MailMergeImageFromBlob()
    Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

    ' Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = New HandleMergeImageFieldFromBlob()

    ' Open a database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Open the data reader. It needs to be in the normal mode that reads all record at once.
    Dim cmd As New OleDbCommand("SELECT * FROM Employees", conn)
    Dim dataReader As IDataReader = cmd.ExecuteReader()

    ' Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees")

    ' Close the database.
    conn.Close()

    doc.Save(MyDir & "MailMerge.MergeImage Out.doc")
End Sub

Private Class HandleMergeImageFieldFromBlob
    Implements IFieldMergingCallback
    Private Sub IFieldMergingCallback_FieldMerging(ByVal args As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' Do nothing.
    End Sub

    ''' <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>
    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' The field value is a byte array, just cast it and create a stream on it.
        Dim imageStream As New MemoryStream(CType(e.FieldValue, Byte()))
        ' Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream
    End Sub
End Class
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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

IFieldMergingCallback Members | Aspose.Words.Reporting 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.Reporting 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.Reporting 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#]

public void MailMergeImageFromBlob()
{
    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.Jet.OLEDB.4.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(MyDir + "MailMerge.MergeImage Out.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;
    }
}
[Visual Basic]

Public Sub MailMergeImageFromBlob()
    Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

    ' Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = New HandleMergeImageFieldFromBlob()

    ' Open a database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Open the data reader. It needs to be in the normal mode that reads all record at once.
    Dim cmd As New OleDbCommand("SELECT * FROM Employees", conn)
    Dim dataReader As IDataReader = cmd.ExecuteReader()

    ' Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees")

    ' Close the database.
    conn.Close()

    doc.Save(MyDir & "MailMerge.MergeImage Out.doc")
End Sub

Private Class HandleMergeImageFieldFromBlob
    Implements IFieldMergingCallback
    Private Sub IFieldMergingCallback_FieldMerging(ByVal args As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' Do nothing.
    End Sub

    ''' <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>
    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' The field value is a byte array, just cast it and create a stream on it.
        Dim imageStream As New MemoryStream(CType(e.FieldValue, Byte()))
        ' Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream
    End Sub
End Class
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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

See Also

IFieldMergingCallback Interface | Aspose.Words.Reporting 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#]

public void MailMergeImageFromBlob()
{
    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.Jet.OLEDB.4.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(MyDir + "MailMerge.MergeImage Out.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;
    }
}
[Visual Basic]

Public Sub MailMergeImageFromBlob()
    Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

    ' Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = New HandleMergeImageFieldFromBlob()

    ' Open a database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Open the data reader. It needs to be in the normal mode that reads all record at once.
    Dim cmd As New OleDbCommand("SELECT * FROM Employees", conn)
    Dim dataReader As IDataReader = cmd.ExecuteReader()

    ' Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees")

    ' Close the database.
    conn.Close()

    doc.Save(MyDir & "MailMerge.MergeImage Out.doc")
End Sub

Private Class HandleMergeImageFieldFromBlob
    Implements IFieldMergingCallback
    Private Sub IFieldMergingCallback_FieldMerging(ByVal args As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' Do nothing.
    End Sub

    ''' <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>
    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' The field value is a byte array, just cast it and create a stream on it.
        Dim imageStream As New MemoryStream(CType(e.FieldValue, Byte()))
        ' Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream
    End Sub
End Class

See Also

IFieldMergingCallback Interface | Aspose.Words.Reporting 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.Reporting.FieldMergingArgsBase
Aspose.Words.Reporting.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#]

public void MailMergeImageFromBlob()
{
    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.Jet.OLEDB.4.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(MyDir + "MailMerge.MergeImage Out.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;
    }
}
[Visual Basic]

Public Sub MailMergeImageFromBlob()
    Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

    ' Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = New HandleMergeImageFieldFromBlob()

    ' Open a database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Open the data reader. It needs to be in the normal mode that reads all record at once.
    Dim cmd As New OleDbCommand("SELECT * FROM Employees", conn)
    Dim dataReader As IDataReader = cmd.ExecuteReader()

    ' Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees")

    ' Close the database.
    conn.Close()

    doc.Save(MyDir & "MailMerge.MergeImage Out.doc")
End Sub

Private Class HandleMergeImageFieldFromBlob
    Implements IFieldMergingCallback
    Private Sub IFieldMergingCallback_FieldMerging(ByVal args As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' Do nothing.
    End Sub

    ''' <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>
    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' The field value is a byte array, just cast it and create a stream on it.
        Dim imageStream As New MemoryStream(CType(e.FieldValue, Byte()))
        ' Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream
    End Sub
End Class

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

ImageFieldMergingArgs Members | Aspose.Words.Reporting 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.Reporting 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.Reporting 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;}

See Also

ImageFieldMergingArgs Class | Aspose.Words.Reporting 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;}

See Also

ImageFieldMergingArgs Class | Aspose.Words.Reporting 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.

See Also

ImageFieldMergingArgs Class | Aspose.Words.Reporting 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#]

public void MailMergeImageFromBlob()
{
    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.Jet.OLEDB.4.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(MyDir + "MailMerge.MergeImage Out.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;
    }
}
[Visual Basic]

Public Sub MailMergeImageFromBlob()
    Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

    ' Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = New HandleMergeImageFieldFromBlob()

    ' Open a database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Open the data reader. It needs to be in the normal mode that reads all record at once.
    Dim cmd As New OleDbCommand("SELECT * FROM Employees", conn)
    Dim dataReader As IDataReader = cmd.ExecuteReader()

    ' Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees")

    ' Close the database.
    conn.Close()

    doc.Save(MyDir & "MailMerge.MergeImage Out.doc")
End Sub

Private Class HandleMergeImageFieldFromBlob
    Implements IFieldMergingCallback
    Private Sub IFieldMergingCallback_FieldMerging(ByVal args As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' Do nothing.
    End Sub

    ''' <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>
    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' The field value is a byte array, just cast it and create a stream on it.
        Dim imageStream As New MemoryStream(CType(e.FieldValue, Byte()))
        ' Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream
    End Sub
End Class

See Also

ImageFieldMergingArgs Class | Aspose.Words.Reporting 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.

See Also

ImageFieldMergingArgs Class | Aspose.Words.Reporting Namespace | MergeFieldImageDimension | MergeFieldImageDimensionUnit


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(MyDir + "MailMerge.CustomDataSource Out.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        mFullName = aFullName;
        mAddress = anAddress;
    }

    public string FullName
    {
        get { return mFullName; }
        set { mFullName = value; }
    }

    public string Address
    {
        get { return mAddress; }
        set { mAddress = value; }
    }

    private string mFullName;
    private string mAddress;
}

/// <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;
}
[Visual Basic]

Public Sub MailMergeCustomDataSource()
    ' Create some data that we will use in the mail merge.
    Dim customers As 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.
    Dim doc As 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.
    Dim customersDataSource As New CustomerMailMergeDataSource(customers)

    ' Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource)

    doc.Save(MyDir & "MailMerge.CustomDataSource Out.doc")
End Sub

''' <summary>
''' An example of a "data entity" class in your application.
''' </summary>
Public Class Customer
    Public Sub New(ByVal aFullName As String, ByVal anAddress As String)
        mFullName = aFullName
        mAddress = anAddress
    End Sub

    Public Property FullName() As String
        Get
            Return mFullName
        End Get
        Set(ByVal value As String)
            mFullName = value
        End Set
    End Property

    Public Property Address() As String
        Get
            Return mAddress
        End Get
        Set(ByVal value As String)
            mAddress = value
        End Set
    End Property

    Private mFullName As String
    Private mAddress As String
End Class

''' <summary>
''' An example of a typed collection that contains your "data" objects.
''' </summary>
Public Class CustomerList
    Inherits ArrayList
    Default Public Shadows Property Item(ByVal index As Integer) As Customer
        Get
            Return CType(MyBase.Item(index), Customer)
        End Get
        Set(ByVal value As Customer)
            MyBase.Item(index) = value
        End Set
    End Property
End Class

''' <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
    Implements IMailMergeDataSource
    Public Sub New(ByVal customers As CustomerList)
        mCustomers = customers

        ' When the data source is initialized, it must be positioned before the first record.
        mRecordIndex= -1
    End Sub

    ''' <summary>
    ''' The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    ''' </summary>
    Public ReadOnly Property TableName() As String Implements IMailMergeDataSource.TableName
        Get
            Return "Customer"
        End Get
    End Property

    ''' <summary>
    ''' Aspose.Words calls this method to get a value for every data field.
    ''' </summary>
    Public Function GetValue(ByVal fieldName As String, <System.Runtime.InteropServices.Out()> ByRef fieldValue As Object) As Boolean Implements IMailMergeDataSource.GetValue
        Select Case fieldName
            Case "FullName"
                fieldValue = mCustomers(mRecordIndex).FullName
                Return True
            Case "Address"
                fieldValue = mCustomers(mRecordIndex).Address
                Return True
            Case Else
                ' A field with this name was not found,
                ' return false to the Aspose.Words mail merge engine.
                fieldValue = Nothing
                Return False
        End Select
    End Function

    ''' <summary>
    ''' A standard implementation for moving to a next record in a collection.
    ''' </summary>
    Public Function MoveNext() As Boolean Implements IMailMergeDataSource.MoveNext
        If (Not IsEof) Then
            mRecordIndex += 1
        End If

        Return ((Not IsEof))
    End Function

    Public Function GetChildDataSource(ByVal tableName As String) As IMailMergeDataSource Implements IMailMergeDataSource.GetChildDataSource
        Return Nothing
    End Function

    Private ReadOnly Property IsEof() As Boolean
        Get
            Return (mRecordIndex >= mCustomers.Count)
        End Get
    End Property

    Private ReadOnly mCustomers As CustomerList
    Private mRecordIndex As Integer
End Class

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

IMailMergeDataSource Members | Aspose.Words.Reporting 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.Reporting 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.Reporting 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(MyDir + "MailMerge.CustomDataSource Out.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        mFullName = aFullName;
        mAddress = anAddress;
    }

    public string FullName
    {
        get { return mFullName; }
        set { mFullName = value; }
    }

    public string Address
    {
        get { return mAddress; }
        set { mAddress = value; }
    }

    private string mFullName;
    private string mAddress;
}

/// <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;
}
[Visual Basic]

Public Sub MailMergeCustomDataSource()
    ' Create some data that we will use in the mail merge.
    Dim customers As 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.
    Dim doc As 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.
    Dim customersDataSource As New CustomerMailMergeDataSource(customers)

    ' Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource)

    doc.Save(MyDir & "MailMerge.CustomDataSource Out.doc")
End Sub

''' <summary>
''' An example of a "data entity" class in your application.
''' </summary>
Public Class Customer
    Public Sub New(ByVal aFullName As String, ByVal anAddress As String)
        mFullName = aFullName
        mAddress = anAddress
    End Sub

    Public Property FullName() As String
        Get
            Return mFullName
        End Get
        Set(ByVal value As String)
            mFullName = value
        End Set
    End Property

    Public Property Address() As String
        Get
            Return mAddress
        End Get
        Set(ByVal value As String)
            mAddress = value
        End Set
    End Property

    Private mFullName As String
    Private mAddress As String
End Class

''' <summary>
''' An example of a typed collection that contains your "data" objects.
''' </summary>
Public Class CustomerList
    Inherits ArrayList
    Default Public Shadows Property Item(ByVal index As Integer) As Customer
        Get
            Return CType(MyBase.Item(index), Customer)
        End Get
        Set(ByVal value As Customer)
            MyBase.Item(index) = value
        End Set
    End Property
End Class

''' <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
    Implements IMailMergeDataSource
    Public Sub New(ByVal customers As CustomerList)
        mCustomers = customers

        ' When the data source is initialized, it must be positioned before the first record.
        mRecordIndex= -1
    End Sub

    ''' <summary>
    ''' The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    ''' </summary>
    Public ReadOnly Property TableName() As String Implements IMailMergeDataSource.TableName
        Get
            Return "Customer"
        End Get
    End Property

    ''' <summary>
    ''' Aspose.Words calls this method to get a value for every data field.
    ''' </summary>
    Public Function GetValue(ByVal fieldName As String, <System.Runtime.InteropServices.Out()> ByRef fieldValue As Object) As Boolean Implements IMailMergeDataSource.GetValue
        Select Case fieldName
            Case "FullName"
                fieldValue = mCustomers(mRecordIndex).FullName
                Return True
            Case "Address"
                fieldValue = mCustomers(mRecordIndex).Address
                Return True
            Case Else
                ' A field with this name was not found,
                ' return false to the Aspose.Words mail merge engine.
                fieldValue = Nothing
                Return False
        End Select
    End Function

    ''' <summary>
    ''' A standard implementation for moving to a next record in a collection.
    ''' </summary>
    Public Function MoveNext() As Boolean Implements IMailMergeDataSource.MoveNext
        If (Not IsEof) Then
            mRecordIndex += 1
        End If

        Return ((Not IsEof))
    End Function

    Public Function GetChildDataSource(ByVal tableName As String) As IMailMergeDataSource Implements IMailMergeDataSource.GetChildDataSource
        Return Nothing
    End Function

    Private ReadOnly Property IsEof() As Boolean
        Get
            Return (mRecordIndex >= mCustomers.Count)
        End Get
    End Property

    Private ReadOnly mCustomers As CustomerList
    Private mRecordIndex As Integer
End Class

See Also

IMailMergeDataSource Interface | Aspose.Words.Reporting 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.Reporting 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(MyDir + "MailMerge.CustomDataSource Out.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        mFullName = aFullName;
        mAddress = anAddress;
    }

    public string FullName
    {
        get { return mFullName; }
        set { mFullName = value; }
    }

    public string Address
    {
        get { return mAddress; }
        set { mAddress = value; }
    }

    private string mFullName;
    private string mAddress;
}

/// <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;
}
[Visual Basic]

Public Sub MailMergeCustomDataSource()
    ' Create some data that we will use in the mail merge.
    Dim customers As 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.
    Dim doc As 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.
    Dim customersDataSource As New CustomerMailMergeDataSource(customers)

    ' Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource)

    doc.Save(MyDir & "MailMerge.CustomDataSource Out.doc")
End Sub

''' <summary>
''' An example of a "data entity" class in your application.
''' </summary>
Public Class Customer
    Public Sub New(ByVal aFullName As String, ByVal anAddress As String)
        mFullName = aFullName
        mAddress = anAddress
    End Sub

    Public Property FullName() As String
        Get
            Return mFullName
        End Get
        Set(ByVal value As String)
            mFullName = value
        End Set
    End Property

    Public Property Address() As String
        Get
            Return mAddress
        End Get
        Set(ByVal value As String)
            mAddress = value
        End Set
    End Property

    Private mFullName As String
    Private mAddress As String
End Class

''' <summary>
''' An example of a typed collection that contains your "data" objects.
''' </summary>
Public Class CustomerList
    Inherits ArrayList
    Default Public Shadows Property Item(ByVal index As Integer) As Customer
        Get
            Return CType(MyBase.Item(index), Customer)
        End Get
        Set(ByVal value As Customer)
            MyBase.Item(index) = value
        End Set
    End Property
End Class

''' <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
    Implements IMailMergeDataSource
    Public Sub New(ByVal customers As CustomerList)
        mCustomers = customers

        ' When the data source is initialized, it must be positioned before the first record.
        mRecordIndex= -1
    End Sub

    ''' <summary>
    ''' The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    ''' </summary>
    Public ReadOnly Property TableName() As String Implements IMailMergeDataSource.TableName
        Get
            Return "Customer"
        End Get
    End Property

    ''' <summary>
    ''' Aspose.Words calls this method to get a value for every data field.
    ''' </summary>
    Public Function GetValue(ByVal fieldName As String, <System.Runtime.InteropServices.Out()> ByRef fieldValue As Object) As Boolean Implements IMailMergeDataSource.GetValue
        Select Case fieldName
            Case "FullName"
                fieldValue = mCustomers(mRecordIndex).FullName
                Return True
            Case "Address"
                fieldValue = mCustomers(mRecordIndex).Address
                Return True
            Case Else
                ' A field with this name was not found,
                ' return false to the Aspose.Words mail merge engine.
                fieldValue = Nothing
                Return False
        End Select
    End Function

    ''' <summary>
    ''' A standard implementation for moving to a next record in a collection.
    ''' </summary>
    Public Function MoveNext() As Boolean Implements IMailMergeDataSource.MoveNext
        If (Not IsEof) Then
            mRecordIndex += 1
        End If

        Return ((Not IsEof))
    End Function

    Public Function GetChildDataSource(ByVal tableName As String) As IMailMergeDataSource Implements IMailMergeDataSource.GetChildDataSource
        Return Nothing
    End Function

    Private ReadOnly Property IsEof() As Boolean
        Get
            Return (mRecordIndex >= mCustomers.Count)
        End Get
    End Property

    Private ReadOnly mCustomers As CustomerList
    Private mRecordIndex As Integer
End Class

See Also

IMailMergeDataSource Interface | Aspose.Words.Reporting 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.Reporting 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(MyDir + "MailMerge.CustomDataSource Out.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        mFullName = aFullName;
        mAddress = anAddress;
    }

    public string FullName
    {
        get { return mFullName; }
        set { mFullName = value; }
    }

    public string Address
    {
        get { return mAddress; }
        set { mAddress = value; }
    }

    private string mFullName;
    private string mAddress;
}

/// <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;
}
[Visual Basic]

Public Sub MailMergeCustomDataSource()
    ' Create some data that we will use in the mail merge.
    Dim customers As 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.
    Dim doc As 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.
    Dim customersDataSource As New CustomerMailMergeDataSource(customers)

    ' Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource)

    doc.Save(MyDir & "MailMerge.CustomDataSource Out.doc")
End Sub

''' <summary>
''' An example of a "data entity" class in your application.
''' </summary>
Public Class Customer
    Public Sub New(ByVal aFullName As String, ByVal anAddress As String)
        mFullName = aFullName
        mAddress = anAddress
    End Sub

    Public Property FullName() As String
        Get
            Return mFullName
        End Get
        Set(ByVal value As String)
            mFullName = value
        End Set
    End Property

    Public Property Address() As String
        Get
            Return mAddress
        End Get
        Set(ByVal value As String)
            mAddress = value
        End Set
    End Property

    Private mFullName As String
    Private mAddress As String
End Class

''' <summary>
''' An example of a typed collection that contains your "data" objects.
''' </summary>
Public Class CustomerList
    Inherits ArrayList
    Default Public Shadows Property Item(ByVal index As Integer) As Customer
        Get
            Return CType(MyBase.Item(index), Customer)
        End Get
        Set(ByVal value As Customer)
            MyBase.Item(index) = value
        End Set
    End Property
End Class

''' <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
    Implements IMailMergeDataSource
    Public Sub New(ByVal customers As CustomerList)
        mCustomers = customers

        ' When the data source is initialized, it must be positioned before the first record.
        mRecordIndex= -1
    End Sub

    ''' <summary>
    ''' The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    ''' </summary>
    Public ReadOnly Property TableName() As String Implements IMailMergeDataSource.TableName
        Get
            Return "Customer"
        End Get
    End Property

    ''' <summary>
    ''' Aspose.Words calls this method to get a value for every data field.
    ''' </summary>
    Public Function GetValue(ByVal fieldName As String, <System.Runtime.InteropServices.Out()> ByRef fieldValue As Object) As Boolean Implements IMailMergeDataSource.GetValue
        Select Case fieldName
            Case "FullName"
                fieldValue = mCustomers(mRecordIndex).FullName
                Return True
            Case "Address"
                fieldValue = mCustomers(mRecordIndex).Address
                Return True
            Case Else
                ' A field with this name was not found,
                ' return false to the Aspose.Words mail merge engine.
                fieldValue = Nothing
                Return False
        End Select
    End Function

    ''' <summary>
    ''' A standard implementation for moving to a next record in a collection.
    ''' </summary>
    Public Function MoveNext() As Boolean Implements IMailMergeDataSource.MoveNext
        If (Not IsEof) Then
            mRecordIndex += 1
        End If

        Return ((Not IsEof))
    End Function

    Public Function GetChildDataSource(ByVal tableName As String) As IMailMergeDataSource Implements IMailMergeDataSource.GetChildDataSource
        Return Nothing
    End Function

    Private ReadOnly Property IsEof() As Boolean
        Get
            Return (mRecordIndex >= mCustomers.Count)
        End Get
    End Property

    Private ReadOnly mCustomers As CustomerList
    Private mRecordIndex As Integer
End Class

See Also

IMailMergeDataSource Interface | Aspose.Words.Reporting 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

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

IMailMergeDataSourceRoot Members | Aspose.Words.Reporting 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.Reporting 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.Reporting 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.

See Also

IMailMergeDataSourceRoot Interface | Aspose.Words.Reporting Namespace


MailMerge Class

Represents the mail merge functionality.

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

System.Object
Aspose.Words.Reporting.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(MyDir + "MailMerge.ExecuteDataTable Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "MailMerge.ExecuteDataTable.doc")

' This example creates a table, but you would normally load table from a database.
Dim table As 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(MyDir & "MailMerge.ExecuteDataTable Out.doc")

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

MailMerge Members | Aspose.Words.Reporting 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.
FieldMergingCallback | Occurs during mail merge when a mail merge field is encountered in the document.
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.
RegionEndTag | Gets or sets a mail merge region end tag.
RegionStartTag | Gets or sets a mail merge region start tag.
RemoveEmptyParagraphs | Obsolete. Specifies whether paragraphs that contained mail merge fields with no data should be removed from the document.
RemoveEmptyRegions | Obsolete. Specifies whether empty mail merge regions should be removed from the document.
RtlCleanupMode | Obsolete. Gets or sets a value indicating how to handle Right-To-Left attributes of mail merge result text runs.
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.

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.

See Also

MailMerge Class | Aspose.Words.Reporting 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.
FieldMergingCallback | Occurs during mail merge when a mail merge field is encountered in the document.
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.
RegionEndTag | Gets or sets a mail merge region end tag.
RegionStartTag | Gets or sets a mail merge region start tag.
RemoveEmptyParagraphs | Obsolete. Specifies whether paragraphs that contained mail merge fields with no data should be removed from the document.
RemoveEmptyRegions | Obsolete. Specifies whether empty mail merge regions should be removed from the document.
RtlCleanupMode | Obsolete. Gets or sets a value indicating how to handle Right-To-Left attributes of mail merge result text runs.
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.

See Also

MailMerge Class | Aspose.Words.Reporting 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;
[Visual Basic]

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;
[Visual Basic]

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;
[Visual Basic]

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields

See Also

MailMerge Class | Aspose.Words.Reporting 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#]

public void MailMergeImageFromBlob()
{
    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.Jet.OLEDB.4.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(MyDir + "MailMerge.MergeImage Out.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;
    }
}
[Visual Basic]

Public Sub MailMergeImageFromBlob()
    Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

    ' Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = New HandleMergeImageFieldFromBlob()

    ' Open a database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Open the data reader. It needs to be in the normal mode that reads all record at once.
    Dim cmd As New OleDbCommand("SELECT * FROM Employees", conn)
    Dim dataReader As IDataReader = cmd.ExecuteReader()

    ' Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees")

    ' Close the database.
    conn.Close()

    doc.Save(MyDir & "MailMerge.MergeImage Out.doc")
End Sub

Private Class HandleMergeImageFieldFromBlob
    Implements IFieldMergingCallback
    Private Sub IFieldMergingCallback_FieldMerging(ByVal args As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' Do nothing.
    End Sub

    ''' <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>
    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' The field value is a byte array, just cast it and create a stream on it.
        Dim imageStream As New MemoryStream(CType(e.FieldValue, Byte()))
        ' Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream
    End Sub
End Class
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.
public void MailMergeInsertHtml()
{
    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 string[] { htmltext });

    // Save resulting document with a new name.
    doc.Save(MyDir + "MailMerge.InsertHtml Out.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 e)
    {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.DocumentFieldName.StartsWith("html"))
        {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.Document);
            builder.MoveToMergeField(e.DocumentFieldName);
            builder.InsertHtml((string)e.FieldValue);

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.Text = "";
        }
    }

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        // Do nothing.
    }
}
[Visual Basic]

' 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.
Public Sub MailMergeInsertHtml()
    Dim doc As New Document(MyDir & "MailMerge.InsertHtml.doc")

    ' Add a handler for the MergeField event.
    doc.MailMerge.FieldMergingCallback = New HandleMergeFieldInsertHtml()

    ' Load some Html from file.
    Dim sr As StreamReader = File.OpenText(MyDir & "MailMerge.HtmlData.html")
    Dim htmltext As String = sr.ReadToEnd()
    sr.Close()

    ' Execute mail merge.
    doc.MailMerge.Execute(New String() { "htmlField1" }, New String() { htmltext })

    ' Save resulting document with a new name.
    doc.Save(MyDir & "MailMerge.InsertHtml Out.doc")
End Sub

Private Class HandleMergeFieldInsertHtml
    Implements IFieldMergingCallback
    ''' <summary>
    ''' This is called when merge field is actually merged with data in the document.
    ''' </summary>
    Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        If e.DocumentFieldName.StartsWith("html") Then
            ' Insert the text for this merge field as HTML data, using DocumentBuilder.
            Dim builder As New DocumentBuilder(e.Document)
            builder.MoveToMergeField(e.DocumentFieldName)
            builder.InsertHtml(CStr(e.FieldValue))

            ' The HTML text itself should not be inserted.
            ' We have already inserted it as an HTML.
            e.Text = ""
        End If
    End Sub

    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' Do nothing.
    End Sub
End Class

See Also

MailMerge Class | Aspose.Words.Reporting 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 add a mapping when a merge field in a document and a data field in a data source have different names.

[C#]

doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource");
[Visual Basic]

doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource")

See Also

MailMerge Class | Aspose.Words.Reporting 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.

See Also

MailMerge Class | Aspose.Words.Reporting Namespace


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;}

See Also

MailMerge Class | Aspose.Words.Reporting 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;}

See Also

MailMerge Class | Aspose.Words.Reporting Namespace


RemoveEmptyParagraphs Property

Aspose.Words

MailMerge.RemoveEmptyParagraphs Property

NOTE: This property is now obsolete.

Use the CleanupOptions property.

Specifies whether paragraphs that contained mail merge fields with no data should be removed from the document.

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

Remarks

When true, paragraphs which contain region start and end merge fields which are otherwise empty are also removed.

This property is obsolete. Please use CleanupOptions instead.

See Also

MailMerge Class | Aspose.Words.Reporting Namespace


RemoveEmptyRegions Property

Aspose.Words

MailMerge.RemoveEmptyRegions Property

NOTE: This property is now obsolete.

Use the CleanupOptions property.

Specifies whether empty mail merge regions should be removed from the document.

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

Remarks

This property is obsolete. Please use CleanupOptions instead.

See Also

MailMerge Class | Aspose.Words.Reporting Namespace


RtlCleanupMode Property

Aspose.Words

MailMerge.RtlCleanupMode Property

NOTE: This property is now obsolete.

This property does not affect anything anymore.

Gets or sets a value indicating how to handle Right-To-Left attributes of mail merge result text runs.

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

See Also

MailMerge Class | Aspose.Words.Reporting 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;
[Visual Basic]

doc.MailMerge.UseNonMergeFields = True

See Also

MailMerge Class | Aspose.Words.Reporting 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.

See Also

MailMerge Class | Aspose.Words.Reporting 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();
[Visual Basic]

doc.MailMerge.DeleteFields()

See Also

MailMerge Class | Aspose.Words.Reporting 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.Reporting 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.

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(MyDir + "MailMerge.CustomDataSource Out.doc");
}

/// <summary>
/// An example of a "data entity" class in your application.
/// </summary>
public class Customer
{
    public Customer(string aFullName, string anAddress)
    {
        mFullName = aFullName;
        mAddress = anAddress;
    }

    public string FullName
    {
        get { return mFullName; }
        set { mFullName = value; }
    }

    public string Address
    {
        get { return mAddress; }
        set { mAddress = value; }
    }

    private string mFullName;
    private string mAddress;
}

/// <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;
}
[Visual Basic]

Public Sub MailMergeCustomDataSource()
    ' Create some data that we will use in the mail merge.
    Dim customers As 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.
    Dim doc As 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.
    Dim customersDataSource As New CustomerMailMergeDataSource(customers)

    ' Now you can pass your data source into Aspose.Words.
    doc.MailMerge.Execute(customersDataSource)

    doc.Save(MyDir & "MailMerge.CustomDataSource Out.doc")
End Sub

''' <summary>
''' An example of a "data entity" class in your application.
''' </summary>
Public Class Customer
    Public Sub New(ByVal aFullName As String, ByVal anAddress As String)
        mFullName = aFullName
        mAddress = anAddress
    End Sub

    Public Property FullName() As String
        Get
            Return mFullName
        End Get
        Set(ByVal value As String)
            mFullName = value
        End Set
    End Property

    Public Property Address() As String
        Get
            Return mAddress
        End Get
        Set(ByVal value As String)
            mAddress = value
        End Set
    End Property

    Private mFullName As String
    Private mAddress As String
End Class

''' <summary>
''' An example of a typed collection that contains your "data" objects.
''' </summary>
Public Class CustomerList
    Inherits ArrayList
    Default Public Shadows Property Item(ByVal index As Integer) As Customer
        Get
            Return CType(MyBase.Item(index), Customer)
        End Get
        Set(ByVal value As Customer)
            MyBase.Item(index) = value
        End Set
    End Property
End Class

''' <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
    Implements IMailMergeDataSource
    Public Sub New(ByVal customers As CustomerList)
        mCustomers = customers

        ' When the data source is initialized, it must be positioned before the first record.
        mRecordIndex= -1
    End Sub

    ''' <summary>
    ''' The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
    ''' </summary>
    Public ReadOnly Property TableName() As String Implements IMailMergeDataSource.TableName
        Get
            Return "Customer"
        End Get
    End Property

    ''' <summary>
    ''' Aspose.Words calls this method to get a value for every data field.
    ''' </summary>
    Public Function GetValue(ByVal fieldName As String, <System.Runtime.InteropServices.Out()> ByRef fieldValue As Object) As Boolean Implements IMailMergeDataSource.GetValue
        Select Case fieldName
            Case "FullName"
                fieldValue = mCustomers(mRecordIndex).FullName
                Return True
            Case "Address"
                fieldValue = mCustomers(mRecordIndex).Address
                Return True
            Case Else
                ' A field with this name was not found,
                ' return false to the Aspose.Words mail merge engine.
                fieldValue = Nothing
                Return False
        End Select
    End Function

    ''' <summary>
    ''' A standard implementation for moving to a next record in a collection.
    ''' </summary>
    Public Function MoveNext() As Boolean Implements IMailMergeDataSource.MoveNext
        If (Not IsEof) Then
            mRecordIndex += 1
        End If

        Return ((Not IsEof))
    End Function

    Public Function GetChildDataSource(ByVal tableName As String) As IMailMergeDataSource Implements IMailMergeDataSource.GetChildDataSource
        Return Nothing
    End Function

    Private ReadOnly Property IsEof() As Boolean
        Get
            Return (mRecordIndex >= mCustomers.Count)
        End Get
    End Property

    Private ReadOnly mCustomers As CustomerList
    Private mRecordIndex As Integer
End Class

See Also

MailMerge Class | Aspose.Words.Reporting 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

Produce multiple documents during mail merge.

[C#]

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Reflection;

using Aspose.Words;

namespace MultipleDocsInMailMerge
{
    class Program
    {
        public static void Main(string[] args)
        {
            //Sample infrastructure.
            string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
            string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;

            ProduceMultipleDocuments(dataDir, "TestFile.doc");
        }

        public static void ProduceMultipleDocuments(string dataDir, string srcDoc)
        {
            // Open the database connection.
            string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataDir + "Customers.mdb";
            OleDbConnection conn = new OleDbConnection(connString);
            conn.Open();
            try
            {
                // Get data from a database.
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers", conn);
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                DataTable data = new DataTable();
                da.Fill(data);

                // Open the template document.
                Document doc = new Document(dataDir + srcDoc);

                int counter = 1;
                // Loop though all records in the data source.
                foreach (DataRow row in data.Rows)
                {
                    // Clone the template instead of loading it from disk (for speed).
                    Document dstDoc = (Document)doc.Clone(true);

                    // Execute mail merge.
                    dstDoc.MailMerge.Execute(row);

                    // Save the document.
                    dstDoc.Save(string.Format(dataDir + "TestFile Out {0}.doc", counter++));
                }
            }
            finally
            {
                // Close the database.
                conn.Close();
            }
        }
    }
}
[Visual Basic]

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports System.Reflection

Imports Aspose.Words

Namespace MultipleDocsInMailMerge
    Friend Class Program
        Public Shared Sub Main(ByVal args() As String)
            'Sample infrastructure.
            Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
            Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath

            ProduceMultipleDocuments(dataDir, "TestFile.doc")
        End Sub

        Public Shared Sub ProduceMultipleDocuments(ByVal dataDir As String, ByVal srcDoc As String)
            ' Open the database connection.
            Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dataDir & "Customers.mdb"
            Dim conn As New OleDbConnection(connString)
            conn.Open()
            Try
                ' Get data from a database.
                Dim cmd As New OleDbCommand("SELECT * FROM Customers", conn)
                Dim da As New OleDbDataAdapter(cmd)
                Dim data As New DataTable()
                da.Fill(data)

                ' Open the template document.
                Dim doc As New Document(dataDir & srcDoc)

                Dim counter As Integer = 1
                ' Loop though all records in the data source.
                For Each row As DataRow In data.Rows
                    ' Clone the template instead of loading it from disk (for speed).
                    Dim dstDoc As Document = CType(doc.Clone(True), Document)

                    ' Execute mail merge.
                    dstDoc.MailMerge.Execute(row)

                    ' Save the document.
                    dstDoc.Save(String.Format(dataDir & "TestFile Out {0}.doc", counter))
                    counter += 1
                Next row
            Finally
                ' Close the database.
                conn.Close()
            End Try
        End Sub
    End Class
End Namespace

See Also

MailMerge Class | Aspose.Words.Reporting 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(MyDir + "MailMerge.ExecuteDataTable Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "MailMerge.ExecuteDataTable.doc")

' This example creates a table, but you would normally load table from a database.
Dim table As 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(MyDir & "MailMerge.ExecuteDataTable Out.doc")

See Also

MailMerge Class | Aspose.Words.Reporting 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

Executes mail merge from an ADO.NET DataView.

[C#]

public void ExecuteDataView()
{
    // Open the document that we want to fill with data.
    Document doc = new Document(MyDir + "MailMerge.ExecuteDataView.doc");

    // Get the data from the database.
    DataTable orderTable = GetOrders();

    // Create a customized view of the data.
    DataView orderView = new DataView(orderTable);
    orderView.RowFilter = "OrderId = 10444";

    // Populate the document with the data.
    doc.MailMerge.Execute(orderView);

    doc.Save(MyDir + "MailMerge.ExecuteDataView Out.doc");
}

private static DataTable GetOrders()
{
    // Open a database connection.
    string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
        DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Create the command.
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM AsposeWordOrders", conn);

    // Fill an ADO.NET table from the command.
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable table = new DataTable();
    da.Fill(table);

    // Close database.
    conn.Close();

    return table;
}
[Visual Basic]

Public Sub ExecuteDataView()
    ' Open the document that we want to fill with data.
    Dim doc As New Document(MyDir & "MailMerge.ExecuteDataView.doc")

    ' Get the data from the database.
    Dim orderTable As DataTable = GetOrders()

    ' Create a customized view of the data.
    Dim orderView As New DataView(orderTable)
    orderView.RowFilter = "OrderId = 10444"

    ' Populate the document with the data.
    doc.MailMerge.Execute(orderView)

    doc.Save(MyDir & "MailMerge.ExecuteDataView Out.doc")
End Sub

Private Shared Function GetOrders() As DataTable
    ' Open a database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Create the command.
    Dim cmd As New OleDbCommand("SELECT * FROM AsposeWordOrders", conn)

    ' Fill an ADO.NET table from the command.
    Dim da As New OleDbDataAdapter(cmd)
    Dim table As New DataTable()
    da.Fill(table)

    ' Close database.
    conn.Close()

    Return table
End Function

See Also

MailMerge Class | Aspose.Words.Reporting 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

Executes mail merge from an ADO.NET DataReader.

[C#]

// Open the template document
Document doc = new Document(MyDir + "MailingLabelsDemo.doc");

// Open the database connection.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
    DatabaseDir + "Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();

// Open the data reader.
OleDbCommand cmd = new OleDbCommand(
    "SELECT TOP 50 * FROM Customers ORDER BY Country, CompanyName", conn);
OleDbDataReader dataReader = cmd.ExecuteReader();

// Perform the mail merge
doc.MailMerge.Execute(dataReader);

// Close database.
dataReader.Close();
conn.Close();

doc.Save(MyDir + "MailMerge.ExecuteDataReader Out.doc");
[Visual Basic]

' Open the template document
Dim doc As New Document(MyDir & "MailingLabelsDemo.doc")

' Open the database connection.
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
Dim conn As New OleDbConnection(connString)
conn.Open()

' Open the data reader.
Dim cmd As New OleDbCommand("SELECT TOP 50 * FROM Customers ORDER BY Country, CompanyName", conn)
Dim dataReader As OleDbDataReader = cmd.ExecuteReader()

' Perform the mail merge
doc.MailMerge.Execute(dataReader)

' Close database.
dataReader.Close()
conn.Close()

doc.Save(MyDir & "MailMerge.ExecuteDataReader Out.doc")

See Also

MailMerge Class | Aspose.Words.Reporting 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[] { "http://www.aspose.com/images/aspose-logo.gif" });

doc.Save(MyDir + "MailMerge.MergeImageFromUrl Out.doc");
[Visual Basic]

Dim doc As 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() { "http://www.aspose.com/images/aspose-logo.gif" })

doc.Save(MyDir & "MailMerge.MergeImageFromUrl Out.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.
doc.Save(Response, "MailMerge.ExecuteArray Out.doc", ContentDisposition.Inline, null);
[Visual Basic]

' Open an existing document.
Dim doc As 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.
doc.Save(Response, "MailMerge.ExecuteArray Out.doc", ContentDisposition.Inline, Nothing)

See Also

MailMerge Class | Aspose.Words.Reporting 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"

See Also

MailMerge Class | Aspose.Words.Reporting 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.Reporting 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

Perform the mail merge and save the result.

[C#]

// Open the template document.
Document doc = new Document(dataDir + "TestFile.doc");

// Fill the document with data from our data sources.
// Using mail merge regions for populating the order items table is required
// because it allows the region to be repeated in the document for each order item.
doc.MailMerge.ExecuteWithRegions(orderItemsDataSource);

// The standard mail merge without regions is used for the delivery address.
doc.MailMerge.Execute(deliveryDataSource);

// Save the output document.
doc.Save(dataDir + "TestFile Out.doc");
[Visual Basic]

' Open the template document.
Dim doc As New Document(dataDir & "TestFile.doc")

' Fill the document with data from our data sources.
' Using mail merge regions for populating the order items table is required
' because it allows the region to be repeated in the document for each order item.
doc.MailMerge.ExecuteWithRegions(orderItemsDataSource)

' The standard mail merge without regions is used for the delivery address.
doc.MailMerge.Execute(deliveryDataSource)

' Save the output document.
doc.Save(dataDir & "TestFile Out.doc")

See Also

MailMerge Class | Aspose.Words.Reporting 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.

See Also

MailMerge Class | Aspose.Words.Reporting 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

Executes a mail merge with repeatable regions from an ADO.NET DataSet.

[C#]

// Open the document.
// For a mail merge with repeatable regions, the document should have mail merge regions
// in the document designated with MERGEFIELD TableStart:MyTableName and TableEnd:MyTableName.
Document doc = new Document(MyDir + "MailMerge.ExecuteWithRegions.doc");

int orderId = 10444;

// Populate tables and add them to the dataset.
// For a mail merge with repeatable regions, DataTable.TableName should be
// set to match the name of the region defined in the document.
DataSet dataSet = new DataSet();

DataTable orderTable = GetTestOrder(orderId);
dataSet.Tables.Add(orderTable);

DataTable orderDetailsTable = GetTestOrderDetails(orderId);
dataSet.Tables.Add(orderDetailsTable);

// This looks through all mail merge regions inside the document and for each
// region tries to find a DataTable with a matching name inside the DataSet.
// If a table is found, its content is merged into the mail merge region in the document.
doc.MailMerge.ExecuteWithRegions(dataSet);

doc.Save(MyDir + "MailMerge.ExecuteWithRegionsDataSet Out.doc");
[Visual Basic]

' Open the document.
' For a mail merge with repeatable regions, the document should have mail merge regions
' in the document designated with MERGEFIELD TableStart:MyTableName and TableEnd:MyTableName.
Dim doc As New Document(MyDir & "MailMerge.ExecuteWithRegions.doc")

Dim orderId As Integer = 10444

' Populate tables and add them to the dataset.
' For a mail merge with repeatable regions, DataTable.TableName should be
' set to match the name of the region defined in the document.
Dim dataSet As New DataSet()

Dim orderTable As DataTable = GetTestOrder(orderId)
dataSet.Tables.Add(orderTable)

Dim orderDetailsTable As DataTable = GetTestOrderDetails(orderId)
dataSet.Tables.Add(orderDetailsTable)

' This looks through all mail merge regions inside the document and for each
' region tries to find a DataTable with a matching name inside the DataSet.
' If a table is found, its content is merged into the mail merge region in the document.
doc.MailMerge.ExecuteWithRegions(dataSet)

doc.Save(MyDir & "MailMerge.ExecuteWithRegionsDataSet Out.doc")

See Also

MailMerge Class | Aspose.Words.Reporting 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

Executes a mail merge with repeatable regions.

[C#]

public void ExecuteWithRegionsDataTable()
{
    Document doc = new Document(MyDir + "MailMerge.ExecuteWithRegions.doc");

    int orderId = 10444;

    // Perform several mail merge operations populating only part of the document each time.

    // Use DataTable as a data source.
    DataTable orderTable = GetTestOrder(orderId);
    doc.MailMerge.ExecuteWithRegions(orderTable);

    // Instead of using DataTable you can create a DataView for custom sort or filter and then mail merge.
    DataView orderDetailsView = new DataView(GetTestOrderDetails(orderId));
    orderDetailsView.Sort = "ExtendedPrice DESC";
    doc.MailMerge.ExecuteWithRegions(orderDetailsView);

    doc.Save(MyDir + "MailMerge.ExecuteWithRegionsDataTable Out.doc");
}

private static DataTable GetTestOrder(int orderId)
{
    DataTable table = ExecuteDataTable(string.Format(
        "SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId));
    table.TableName = "Orders";
    return table;
}

private static DataTable GetTestOrderDetails(int orderId)
{
    DataTable table = ExecuteDataTable(string.Format(
        "SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId));
    table.TableName = "OrderDetails";
    return table;
}

/// <summary>
/// Utility function that creates a connection, command,
/// executes the command and return the result in a DataTable.
/// </summary>
private static DataTable ExecuteDataTable(string commandText)
{
    // Open the database connection.
    string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
        DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Create and execute a command.
    OleDbCommand cmd = new OleDbCommand(commandText, conn);
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable table = new DataTable();
    da.Fill(table);

    // Close the database.
    conn.Close();

    return table;
}
[Visual Basic]

Public Sub ExecuteWithRegionsDataTable()
    Dim doc As New Document(MyDir & "MailMerge.ExecuteWithRegions.doc")

    Dim orderId As Integer = 10444

    ' Perform several mail merge operations populating only part of the document each time.

    ' Use DataTable as a data source.
    Dim orderTable As DataTable = GetTestOrder(orderId)
    doc.MailMerge.ExecuteWithRegions(orderTable)

    ' Instead of using DataTable you can create a DataView for custom sort or filter and then mail merge.
    Dim orderDetailsView As New DataView(GetTestOrderDetails(orderId))
    orderDetailsView.Sort = "ExtendedPrice DESC"
    doc.MailMerge.ExecuteWithRegions(orderDetailsView)

    doc.Save(MyDir & "MailMerge.ExecuteWithRegionsDataTable Out.doc")
End Sub

Private Shared Function GetTestOrder(ByVal orderId As Integer) As DataTable
    Dim table As DataTable = ExecuteDataTable(String.Format("SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId))
    table.TableName = "Orders"
    Return table
End Function

Private Shared Function GetTestOrderDetails(ByVal orderId As Integer) As DataTable
    Dim table As DataTable = ExecuteDataTable(String.Format("SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId))
    table.TableName = "OrderDetails"
    Return table
End Function

''' <summary>
''' Utility function that creates a connection, command,
''' executes the command and return the result in a DataTable.
''' </summary>
Private Shared Function ExecuteDataTable(ByVal commandText As String) As DataTable
    ' Open the database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Create and execute a command.
    Dim cmd As New OleDbCommand(commandText, conn)
    Dim da As New OleDbDataAdapter(cmd)
    Dim table As New DataTable()
    da.Fill(table)

    ' Close the database.
    conn.Close()

    Return table
End Function

See Also

MailMerge Class | Aspose.Words.Reporting 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

Executes a mail merge with repeatable regions.

[C#]

public void ExecuteWithRegionsDataTable()
{
    Document doc = new Document(MyDir + "MailMerge.ExecuteWithRegions.doc");

    int orderId = 10444;

    // Perform several mail merge operations populating only part of the document each time.

    // Use DataTable as a data source.
    DataTable orderTable = GetTestOrder(orderId);
    doc.MailMerge.ExecuteWithRegions(orderTable);

    // Instead of using DataTable you can create a DataView for custom sort or filter and then mail merge.
    DataView orderDetailsView = new DataView(GetTestOrderDetails(orderId));
    orderDetailsView.Sort = "ExtendedPrice DESC";
    doc.MailMerge.ExecuteWithRegions(orderDetailsView);

    doc.Save(MyDir + "MailMerge.ExecuteWithRegionsDataTable Out.doc");
}

private static DataTable GetTestOrder(int orderId)
{
    DataTable table = ExecuteDataTable(string.Format(
        "SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId));
    table.TableName = "Orders";
    return table;
}

private static DataTable GetTestOrderDetails(int orderId)
{
    DataTable table = ExecuteDataTable(string.Format(
        "SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId));
    table.TableName = "OrderDetails";
    return table;
}

/// <summary>
/// Utility function that creates a connection, command,
/// executes the command and return the result in a DataTable.
/// </summary>
private static DataTable ExecuteDataTable(string commandText)
{
    // Open the database connection.
    string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
        DatabaseDir + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Create and execute a command.
    OleDbCommand cmd = new OleDbCommand(commandText, conn);
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable table = new DataTable();
    da.Fill(table);

    // Close the database.
    conn.Close();

    return table;
}
[Visual Basic]

Public Sub ExecuteWithRegionsDataTable()
    Dim doc As New Document(MyDir & "MailMerge.ExecuteWithRegions.doc")

    Dim orderId As Integer = 10444

    ' Perform several mail merge operations populating only part of the document each time.

    ' Use DataTable as a data source.
    Dim orderTable As DataTable = GetTestOrder(orderId)
    doc.MailMerge.ExecuteWithRegions(orderTable)

    ' Instead of using DataTable you can create a DataView for custom sort or filter and then mail merge.
    Dim orderDetailsView As New DataView(GetTestOrderDetails(orderId))
    orderDetailsView.Sort = "ExtendedPrice DESC"
    doc.MailMerge.ExecuteWithRegions(orderDetailsView)

    doc.Save(MyDir & "MailMerge.ExecuteWithRegionsDataTable Out.doc")
End Sub

Private Shared Function GetTestOrder(ByVal orderId As Integer) As DataTable
    Dim table As DataTable = ExecuteDataTable(String.Format("SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId))
    table.TableName = "Orders"
    Return table
End Function

Private Shared Function GetTestOrderDetails(ByVal orderId As Integer) As DataTable
    Dim table As DataTable = ExecuteDataTable(String.Format("SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId))
    table.TableName = "OrderDetails"
    Return table
End Function

''' <summary>
''' Utility function that creates a connection, command,
''' executes the command and return the result in a DataTable.
''' </summary>
Private Shared Function ExecuteDataTable(ByVal commandText As String) As DataTable
    ' Open the database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Create and execute a command.
    Dim cmd As New OleDbCommand(commandText, conn)
    Dim da As New OleDbDataAdapter(cmd)
    Dim table As New DataTable()
    da.Fill(table)

    ' Close the database.
    conn.Close()

    Return table
End Function

See Also

MailMerge Class | Aspose.Words.Reporting 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#]

public void MailMergeImageFromBlob()
{
    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.Jet.OLEDB.4.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(MyDir + "MailMerge.MergeImage Out.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;
    }
}
[Visual Basic]

Public Sub MailMergeImageFromBlob()
    Dim doc As New Document(MyDir & "MailMerge.MergeImage.doc")

    ' Set up the event handler for image fields.
    doc.MailMerge.FieldMergingCallback = New HandleMergeImageFieldFromBlob()

    ' Open a database connection.
    Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DatabaseDir & "Northwind.mdb"
    Dim conn As New OleDbConnection(connString)
    conn.Open()

    ' Open the data reader. It needs to be in the normal mode that reads all record at once.
    Dim cmd As New OleDbCommand("SELECT * FROM Employees", conn)
    Dim dataReader As IDataReader = cmd.ExecuteReader()

    ' Perform mail merge.
    doc.MailMerge.ExecuteWithRegions(dataReader, "Employees")

    ' Close the database.
    conn.Close()

    doc.Save(MyDir & "MailMerge.MergeImage Out.doc")
End Sub

Private Class HandleMergeImageFieldFromBlob
    Implements IFieldMergingCallback
    Private Sub IFieldMergingCallback_FieldMerging(ByVal args As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
        ' Do nothing.
    End Sub

    ''' <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>
    Private Sub ImageFieldMerging(ByVal e As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
        ' The field value is a byte array, just cast it and create a stream on it.
        Dim imageStream As New MemoryStream(CType(e.FieldValue, Byte()))
        ' Now the mail merge engine will retrieve the image from the stream.
        e.ImageStream = imageStream
    End Sub
End Class

See Also

MailMerge Class | Aspose.Words.Reporting 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"

See Also

MailMerge Class | Aspose.Words.Reporting 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.

Example

Shows how to get names of all merge fields in a document.

[C#]

string[] fieldNames = doc.MailMerge.GetFieldNames();
[Visual Basic]

Dim fieldNames() As String = doc.MailMerge.GetFieldNames()

See Also

MailMerge Class | Aspose.Words.Reporting Namespace


MailMergeCleanupOptions Enumeration

Specifies options that determine what items are removed during mail merge.

[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;
[Visual Basic]

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;
[Visual Basic]

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;
[Visual Basic]

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

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

Aspose.Words.Reporting 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.Reporting

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

See Also

Aspose.Words.Reporting 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.Reporting.MappedDataFieldCollection

[Visual Basic]
Public Class MappedDataFieldCollection
Implements IEnumerable
[C#]
public class MappedDataFieldCollection : 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 add a mapping when a merge field in a document and a data field in a data source have different names.

[C#]

doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource");
[Visual Basic]

doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource")

Requirements

Namespace: Aspose.Words.Reporting

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

See Also

MappedDataFieldCollection Members | Aspose.Words.Reporting 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.Reporting 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.Reporting 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;}

See Also

MappedDataFieldCollection Class | Aspose.Words.Reporting 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;}

See Also

MappedDataFieldCollection Class | Aspose.Words.Reporting 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.Reporting 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 add a mapping when a merge field in a document and a data field in a data source have different names.

[C#]

doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource");
[Visual Basic]

doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource")

See Also

MappedDataFieldCollection Class | Aspose.Words.Reporting Namespace


MappedDataFieldCollection.Clear Method

Removes all elements from the collection.

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

See Also

MappedDataFieldCollection Class | Aspose.Words.Reporting 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.

See Also

MappedDataFieldCollection Class | Aspose.Words.Reporting 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.

See Also

MappedDataFieldCollection Class | Aspose.Words.Reporting 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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.GetEnumerator

See Also

MappedDataFieldCollection Class | Aspose.Words.Reporting 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.

See Also

MappedDataFieldCollection 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.
FontSavingArgs | Provides data for the FontSaving event.
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.
PdfDigitalSignatureDetails | Contains details for signing a PDF document with a digital signature.
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.
SwfSaveOptions | Can be used to specify additional options when saving a document into the Swf format.
SwfToolTips | Allows to specify tooltips displayed in the Aspose.Words SWF Document Viewer.
TxtSaveOptions | Can be used to specify additional options when saving a document into the Text format.
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.
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
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.
HtmlElementSizeOutputMode | Specifies how Aspose.Words exports element widths and heights to HTML, MHTML and EPUB.
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.
OoxmlCompliance | Allows to specify which OOXML specification will be used when saving in the DOCX format.
PdfCompliance | Specifies the PDF standards compliance level.
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.
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 |
SwfLeftPaneControlFlags | Specifies what buttons are displayed on the left panel of SWF viewer.
SwfTopPaneControlFlags | Specifies what buttons are displayed on the top panel of SWF viewer.
SwfViewerControlIdentifier | Identifies each control in the Aspose.Words SWF Document Viewer.
TiffCompression | Specifies what type of compression to apply when saving page images into a TIFF file.


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
[C#]
public class BookmarksOutlineLevelCollection : 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 | 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 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 | 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 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.

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

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

[Visual Basic]
NotOverridable Public Function GetEnumerator() As IEnumerator _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.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


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

Members

Member Name | Description | Value
Fallback | If fallback shape is available for DrawingML, Aspose.Words renders fallback shape instead of the DrawingML. This is the default mode. | 0
DrawingML | Aspose.Words ignores fallback shape of DrawingML and renders DrawingML itself. | 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

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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.

[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");

HtmlSaveOptions saveOptions = new HtmlSaveOptions(SaveFormat.Html);
saveOptions.ExportHeadersFootersMode = ExportHeadersFootersMode.None; // Disables exporting headers and footers.

doc.Save(MyDir + "HeaderFooter.DisableHeadersFooters Out.html", saveOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "HeaderFooter.RemoveFooters.doc")

Dim saveOptions As New HtmlSaveOptions(SaveFormat.Html)
saveOptions.ExportHeadersFootersMode = ExportHeadersFootersMode.None ' Disables exporting headers and footers.

doc.Save(MyDir & "HeaderFooter.DisableHeadersFooters Out.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


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(MyDir + "Document.SaveWithFontsExport Out.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);
    }
}
[Visual Basic]

Public Sub SaveHtmlExportFonts()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Set the option to export font resources.
    Dim options As New HtmlSaveOptions(SaveFormat.Mhtml)
    options.ExportFontResources = True
    ' Create and pass the object which implements the handler methods.
    options.FontSavingCallback = New HandleFontSaving()

    doc.Save(MyDir & "Document.SaveWithFontsExport Out.html", options)
End Sub

Public Class HandleFontSaving
    Implements IFontSavingCallback
    Private Sub IFontSavingCallback_FontSaving(ByVal args As FontSavingArgs) Implements IFontSavingCallback.FontSaving
        ' 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)
    End Sub
End Class

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(MyDir + "Document.SaveWithFontsExport Out.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);
    }
}
[Visual Basic]

Public Sub SaveHtmlExportFonts()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Set the option to export font resources.
    Dim options As New HtmlSaveOptions(SaveFormat.Mhtml)
    options.ExportFontResources = True
    ' Create and pass the object which implements the handler methods.
    options.FontSavingCallback = New HandleFontSaving()

    doc.Save(MyDir & "Document.SaveWithFontsExport Out.html", options)
End Sub

Public Class HandleFontSaving
    Implements IFontSavingCallback
    Private Sub IFontSavingCallback_FontSaving(ByVal args As FontSavingArgs) Implements IFontSavingCallback.FontSaving
        ' 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)
    End Sub
End Class

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(MyDir + "Document.SaveWithFontsExport Out.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);
    }
}
[Visual Basic]

Public Sub SaveHtmlExportFonts()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Set the option to export font resources.
    Dim options As New HtmlSaveOptions(SaveFormat.Mhtml)
    options.ExportFontResources = True
    ' Create and pass the object which implements the handler methods.
    options.FontSavingCallback = New HandleFontSaving()

    doc.Save(MyDir & "Document.SaveWithFontsExport Out.html", options)
End Sub

Public Class HandleFontSaving
    Implements IFontSavingCallback
    Private Sub IFontSavingCallback_FontSaving(ByVal args As FontSavingArgs) Implements IFontSavingCallback.FontSaving
        ' 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)
    End Sub
End Class

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


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


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.HtmlFixedSaveOptions

[Visual Basic]
Public Class HtmlFixedSaveOptions
Inherits SaveOptions
[C#]
public class HtmlFixedSaveOptions : SaveOptions

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 this class that can be used to save a document in the HtmlFixed format.

Public Instance Properties

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.
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.
FontFormat | Gets or sets ExportFontFormat used for font exporting. Default value is Woff.
JpegQuality | Gets or sets a value determining the quality of the JPEG images inside Html document.
MetafileRenderingMode | Obsolete. Gets or sets a value determining how metafile images should be rendered.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


HtmlFixedSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the HtmlFixed format.

[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

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.
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.
FontFormat | Gets or sets ExportFontFormat used for font exporting. Default value is Woff.
JpegQuality | Gets or sets a value determining the quality of the JPEG images inside Html document.
MetafileRenderingMode | Obsolete. Gets or sets a value determining how metafile images should be rendered.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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;}

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;}

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;}

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;}

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


JpegQuality Property

Aspose.Words

HtmlFixedSaveOptions.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 Html 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

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingMode Property

Aspose.Words

HtmlFixedSaveOptions.MetafileRenderingMode Property

NOTE: This property is now obsolete.

Use MetafileRenderingOptions.RenderingMode property.

Gets or sets a value determining how metafile images should be rendered.

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

Remarks

Has effect only when a document contains metafile images.

Use this property to get or set the mode of how metafile images inside a document should be rendered when saving in Html format.

The default value is VectorWithFallback.

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Property

Aspose.Words

HtmlFixedSaveOptions.MetafileRenderingOptions Property

Allows to specify metafile rendering options.

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

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Property

Aspose.Words

HtmlFixedSaveOptions.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;}

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


PageCount Property

Aspose.Words

HtmlFixedSaveOptions.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;}

See Also

HtmlFixedSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

HtmlFixedSaveOptions.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;}

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


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


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(MyDir, "Images");

// 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(MyDir + "Document.SaveWithOptions Out.html", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

' This is the directory we want the exported images to be saved to.
Dim imagesDir As String = Path.Combine(MyDir, "Images")

' The folder specified needs to exist and should be empty.
If Directory.Exists(imagesDir) Then
    Directory.Delete(imagesDir, True)
End If

Directory.CreateDirectory(imagesDir)

' Set an option to export form fields as plain text, not as HTML input elements.
Dim options As New HtmlSaveOptions(SaveFormat.Html)
options.ExportTextInputFormFieldAsText = True
options.ImagesFolder = imagesDir

doc.Save(MyDir & "Document.SaveWithOptions Out.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(MyDir + "Document.SaveWithCustomImagesExport Out.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs e)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (e.ImageFileName.EndsWith(".jpeg"))
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg");
    }
}
[Visual Basic]

Public Sub SaveHtmlExportImages()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Create and pass the object which implements the handler methods.
    Dim options As New HtmlSaveOptions(SaveFormat.Html)
    options.ImageSavingCallback = New HandleImageSaving()

    doc.Save(MyDir & "Document.SaveWithCustomImagesExport Out.html", options)
End Sub

Public Class HandleImageSaving
    Implements IImageSavingCallback
    Private Sub IImageSavingCallback_ImageSaving(ByVal e As ImageSavingArgs) Implements IImageSavingCallback.ImageSaving
        ' Change any images in the document being exported with the extension of "jpeg" to "jpg".
        If e.ImageFileName.EndsWith(".jpeg") Then
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg")
        End If
    End Sub
End Class
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 = System.Text.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(MyDir + "Document.EpubConversion Out.epub", saveOptions);
[Visual Basic]

' Open an existing document from disk.
Dim doc As 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.
Dim saveOptions As New HtmlSaveOptions()

' Specify the desired encoding.
saveOptions.Encoding = System.Text.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(MyDir & "Document.EpubConversion Out.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.
AllowNegativeLeftIndent | Obsolete. Specifies whether negative left and right indents of paragraphs are normalized when saving to HTML, MHTML or EPUB. Default value is false.
CssSavingCallback | Allows to control how CSS styles are saved when a document is saved to HTML, MHTML or EPUB.
CssStyleSheetFileName | Specifies the name of the Cascading Style Sheet (CSS) file written when the 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.
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.
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.
ExportHeadersFooters | Obsolete. Specifies whether to output headers and footers to HTML, MHTML or EPUB. Default value is true for HTML/MHTML and false for EPUB.
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.
ExportMetafileAsRaster | Specifies whether to convert metafiles into raster images when exporting to HTML, MHTML or EPUB. Default value is true.
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.
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 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.
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.
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 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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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 = System.Text.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(MyDir + "Document.EpubConversion Out.epub", saveOptions);
[Visual Basic]

' Open an existing document from disk.
Dim doc As 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.
Dim saveOptions As New HtmlSaveOptions()

' Specify the desired encoding.
saveOptions.Encoding = System.Text.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(MyDir & "Document.EpubConversion Out.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.
AllowNegativeLeftIndent | Obsolete. Specifies whether negative left and right indents of paragraphs are normalized when saving to HTML, MHTML or EPUB. Default value is false.
CssSavingCallback | Allows to control how CSS styles are saved when a document is saved to HTML, MHTML or EPUB.
CssStyleSheetFileName | Specifies the name of the Cascading Style Sheet (CSS) file written when the 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.
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.
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.
ExportHeadersFooters | Obsolete. Specifies whether to output headers and footers to HTML, MHTML or EPUB. Default value is true for HTML/MHTML and false for EPUB.
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.
ExportMetafileAsRaster | Specifies whether to convert metafiles into raster images when exporting to HTML, MHTML or EPUB. Default value is true.
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.
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 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.
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.
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 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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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


AllowNegativeLeftIndent Property

Aspose.Words

HtmlSaveOptions.AllowNegativeLeftIndent Property

NOTE: This property is now obsolete.

Use AllowNegativeIndent

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 AllowNegativeLeftIndent As Boolean
[C#]
public bool AllowNegativeLeftIndent {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


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 name of the Cascading Style Sheet (CSS) file written when the 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 you don't specify a value for this property, then the style sheet file will have the same name as the HTML document name, but with a ".css" extension.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | 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 = System.Text.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(MyDir + "Document.EpubConversion Out.epub", saveOptions);
[Visual Basic]

' Open an existing document from disk.
Dim doc As 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.
Dim saveOptions As New HtmlSaveOptions()

' Specify the desired encoding.
saveOptions.Encoding = System.Text.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(MyDir & "Document.EpubConversion Out.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 = System.Text.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(MyDir + "Document.EpubConversion Out.epub", saveOptions);
[Visual Basic]

' Open an existing document from disk.
Dim doc As 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.
Dim saveOptions As New HtmlSaveOptions()

' Specify the desired encoding.
saveOptions.Encoding = System.Text.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(MyDir & "Document.EpubConversion Out.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


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 = System.Text.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(MyDir + "Document.EpubConversion Out.epub", saveOptions);
[Visual Basic]

' Open an existing document from disk.
Dim doc As 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.
Dim saveOptions As New HtmlSaveOptions()

' Specify the desired encoding.
saveOptions.Encoding = System.Text.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(MyDir & "Document.EpubConversion Out.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.

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(MyDir + "Document.SaveWithFontsExport Out.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);
    }
}
[Visual Basic]

Public Sub SaveHtmlExportFonts()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Set the option to export font resources.
    Dim options As New HtmlSaveOptions(SaveFormat.Mhtml)
    options.ExportFontResources = True
    ' Create and pass the object which implements the handler methods.
    options.FontSavingCallback = New HandleFontSaving()

    doc.Save(MyDir & "Document.SaveWithFontsExport Out.html", options)
End Sub

Public Class HandleFontSaving
    Implements IFontSavingCallback
    Private Sub IFontSavingCallback_FontSaving(ByVal args As FontSavingArgs) Implements IFontSavingCallback.FontSaving
        ' 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)
    End Sub
End Class

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | FontResourcesSubsettingSizeThreshold


ExportHeadersFooters Property

Aspose.Words

HtmlSaveOptions.ExportHeadersFooters Property

NOTE: This property is now obsolete.

Use ExportHeadersFootersMode property

Specifies whether to output headers and footers to HTML, MHTML or EPUB. Default value is true for HTML/MHTML and false for EPUB.

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

Remarks

This property is obsolete. Please use ExportHeadersFootersMode instead.

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");

HtmlSaveOptions saveOptions = new HtmlSaveOptions(SaveFormat.Html);
saveOptions.ExportHeadersFootersMode = ExportHeadersFootersMode.None; // Disables exporting headers and footers.

doc.Save(MyDir + "HeaderFooter.DisableHeadersFooters Out.html", saveOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "HeaderFooter.RemoveFooters.doc")

Dim saveOptions As New HtmlSaveOptions(SaveFormat.Html)
saveOptions.ExportHeadersFootersMode = ExportHeadersFootersMode.None ' Disables exporting headers and footers.

doc.Save(MyDir & "HeaderFooter.DisableHeadersFooters Out.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


ExportMetafileAsRaster Property

Aspose.Words

HtmlSaveOptions.ExportMetafileAsRaster Property

Specifies whether to convert metafiles into raster images when exporting to HTML, MHTML or EPUB. Default value is true.

[Visual Basic]
Public Property ExportMetafileAsRaster As Boolean
[C#]
public bool ExportMetafileAsRaster {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. Setting this property to false causes metafiles to be exported to HTML without conversion.

Some image transforms, in particular image cropping, will not be applied to metafile images if this property is false.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ImageResolution | ScaleImageToShapeSize


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


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(MyDir, "Images");

// 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(MyDir + "Document.SaveWithOptions Out.html", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

' This is the directory we want the exported images to be saved to.
Dim imagesDir As String = Path.Combine(MyDir, "Images")

' The folder specified needs to exist and should be empty.
If Directory.Exists(imagesDir) Then
    Directory.Delete(imagesDir, True)
End If

Directory.CreateDirectory(imagesDir)

' Set an option to export form fields as plain text, not as HTML input elements.
Dim options As New HtmlSaveOptions(SaveFormat.Html)
options.ExportTextInputFormFieldAsText = True
options.ImagesFolder = imagesDir

doc.Save(MyDir & "Document.SaveWithOptions Out.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 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(MyDir + "Document.SaveWithFontsExport Out.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);
    }
}
[Visual Basic]

Public Sub SaveHtmlExportFonts()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Set the option to export font resources.
    Dim options As New HtmlSaveOptions(SaveFormat.Mhtml)
    options.ExportFontResources = True
    ' Create and pass the object which implements the handler methods.
    options.FontSavingCallback = New HandleFontSaving()

    doc.Save(MyDir & "Document.SaveWithFontsExport Out.html", options)
End Sub

Public Class HandleFontSaving
    Implements IFontSavingCallback
    Private Sub IFontSavingCallback_FontSaving(ByVal args As FontSavingArgs) Implements IFontSavingCallback.FontSaving
        ' 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)
    End Sub
End Class

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.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | 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.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ExportFontResources | FontsFolder | FontSavingCallback


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 when ExportMetafileAsRaster is true. 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(MyDir + "Document.SaveWithCustomImagesExport Out.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs e)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (e.ImageFileName.EndsWith(".jpeg"))
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg");
    }
}
[Visual Basic]

Public Sub SaveHtmlExportImages()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Create and pass the object which implements the handler methods.
    Dim options As New HtmlSaveOptions(SaveFormat.Html)
    options.ImageSavingCallback = New HandleImageSaving()

    doc.Save(MyDir & "Document.SaveWithCustomImagesExport Out.html", options)
End Sub

Public Class HandleImageSaving
    Implements IImageSavingCallback
    Private Sub IImageSavingCallback_ImageSaving(ByVal e As ImageSavingArgs) Implements IImageSavingCallback.ImageSaving
        ' Change any images in the document being exported with the extension of "jpeg" to "jpg".
        If e.ImageFileName.EndsWith(".jpeg") Then
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg")
        End If
    End Sub
End Class

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.

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(MyDir, "Images");

// 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(MyDir + "Document.SaveWithOptions Out.html", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

' This is the directory we want the exported images to be saved to.
Dim imagesDir As String = Path.Combine(MyDir, "Images")

' The folder specified needs to exist and should be empty.
If Directory.Exists(imagesDir) Then
    Directory.Delete(imagesDir, True)
End If

Directory.CreateDirectory(imagesDir)

' Set an option to export form fields as plain text, not as HTML input elements.
Dim options As New HtmlSaveOptions(SaveFormat.Html)
options.ExportTextInputFormFieldAsText = True
options.ImagesFolder = imagesDir

doc.Save(MyDir & "Document.SaveWithOptions Out.html", options)

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | 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.

See Also

HtmlSaveOptions Class | Aspose.Words.Saving Namespace | ImagesFolder | ImageSavingCallback


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 = System.Text.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(MyDir + "Document.EpubConversion Out.epub", saveOptions);
[Visual Basic]

' Open an existing document from disk.
Dim doc As 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.
Dim saveOptions As New HtmlSaveOptions()

' Specify the desired encoding.
saveOptions.Encoding = System.Text.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(MyDir & "Document.EpubConversion Out.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


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(MyDir + "Document.SaveWithFontsExport Out.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);
    }
}
[Visual Basic]

Public Sub SaveHtmlExportFonts()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Set the option to export font resources.
    Dim options As New HtmlSaveOptions(SaveFormat.Mhtml)
    options.ExportFontResources = True
    ' Create and pass the object which implements the handler methods.
    options.FontSavingCallback = New HandleFontSaving()

    doc.Save(MyDir & "Document.SaveWithFontsExport Out.html", options)
End Sub

Public Class HandleFontSaving
    Implements IFontSavingCallback
    Private Sub IFontSavingCallback_FontSaving(ByVal args As FontSavingArgs) Implements IFontSavingCallback.FontSaving
        ' 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)
    End Sub
End Class

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(MyDir + "Document.SaveWithFontsExport Out.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);
    }
}
[Visual Basic]

Public Sub SaveHtmlExportFonts()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Set the option to export font resources.
    Dim options As New HtmlSaveOptions(SaveFormat.Mhtml)
    options.ExportFontResources = True
    ' Create and pass the object which implements the handler methods.
    options.FontSavingCallback = New HandleFontSaving()

    doc.Save(MyDir & "Document.SaveWithFontsExport Out.html", options)
End Sub

Public Class HandleFontSaving
    Implements IFontSavingCallback
    Private Sub IFontSavingCallback_FontSaving(ByVal args As FontSavingArgs) Implements IFontSavingCallback.FontSaving
        ' 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)
    End Sub
End Class

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(MyDir + "Document.SaveWithCustomImagesExport Out.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs e)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (e.ImageFileName.EndsWith(".jpeg"))
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg");
    }
}
[Visual Basic]

Public Sub SaveHtmlExportImages()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Create and pass the object which implements the handler methods.
    Dim options As New HtmlSaveOptions(SaveFormat.Html)
    options.ImageSavingCallback = New HandleImageSaving()

    doc.Save(MyDir & "Document.SaveWithCustomImagesExport Out.html", options)
End Sub

Public Class HandleImageSaving
    Implements IImageSavingCallback
    Private Sub IImageSavingCallback_ImageSaving(ByVal e As ImageSavingArgs) Implements IImageSavingCallback.ImageSaving
        ' Change any images in the document being exported with the extension of "jpeg" to "jpg".
        If e.ImageFileName.EndsWith(".jpeg") Then
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg")
        End If
    End Sub
End Class

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(MyDir + "Document.SaveWithCustomImagesExport Out.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs e)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (e.ImageFileName.EndsWith(".jpeg"))
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg");
    }
}
[Visual Basic]

Public Sub SaveHtmlExportImages()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Create and pass the object which implements the handler methods.
    Dim options As New HtmlSaveOptions(SaveFormat.Html)
    options.ImageSavingCallback = New HandleImageSaving()

    doc.Save(MyDir & "Document.SaveWithCustomImagesExport Out.html", options)
End Sub

Public Class HandleImageSaving
    Implements IImageSavingCallback
    Private Sub IImageSavingCallback_ImageSaving(ByVal e As ImageSavingArgs) Implements IImageSavingCallback.ImageSaving
        ' Change any images in the document being exported with the extension of "jpeg" to "jpg".
        If e.ImageFileName.EndsWith(".jpeg") Then
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg")
        End If
    End Sub
End Class

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

Example

Applies LZW compression, saves to grayscale TIFF image with specified brightness and contrast.

[C#]

private static void SaveGrayscaleTIFFwithLZW(Document doc, string dataDir, float brightness, float contrast)
{
    // Select the TIFF format with 100 dpi.
    ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff);
    imgOpttiff.Resolution = 100;

    // Select LZW compression.
    imgOpttiff.TiffCompression = TiffCompression.Lzw;

    // Apply grayscale filter.
    imgOpttiff.ImageColorMode = ImageColorMode.Grayscale;

    // Set brightness and contrast.
    imgOpttiff.ImageBrightness = brightness;
    imgOpttiff.ImageContrast = contrast;

    // Save multipage grayscale TIFF.
    doc.Save(string.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff);
}
[Visual Basic]

Private Shared Sub SaveGrayscaleTIFFwithLZW(ByVal doc As Document, ByVal dataDir As String, ByVal brightness As Single, ByVal contrast As Single)
    ' Select the TIFF format with 100 dpi.
    Dim imgOpttiff As New ImageSaveOptions(SaveFormat.Tiff)
    imgOpttiff.Resolution = 100

    ' Select LZW compression.
    imgOpttiff.TiffCompression = TiffCompression.Lzw

    ' Apply grayscale filter.
    imgOpttiff.ImageColorMode = ImageColorMode.Grayscale

    ' Set brightness and contrast.
    imgOpttiff.ImageBrightness = brightness
    imgOpttiff.ImageContrast = contrast

    ' Save multipage grayscale TIFF.
    doc.Save(String.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff)
End Sub

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

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.ImageSaveOptions

[Visual Basic]
Public Class ImageSaveOptions
Inherits SaveOptions
[C#]
public class ImageSaveOptions : SaveOptions

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);
options.Resolution = 300;
options.PageCount = 1;

doc.Save(MyDir + "Rendering.SaveToImageResolution Out.png", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Png)
options.Resolution = 300
options.PageCount = 1

doc.Save(MyDir & "Rendering.SaveToImageResolution Out.png", options)
Converts a page of a Word document into JPEG images of different qualities.
[C#]

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

ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg);

// Try worst quality.
options.JpegQuality = 0;
doc.Save(MyDir + "Rendering.SaveToImageJpegQuality0 Out.jpeg", options);

// Try best quality.
options.JpegQuality = 100;
doc.Save(MyDir + "Rendering.SaveToImageJpegQuality100 Out.jpeg", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Jpeg)

' Try worst quality.
options.JpegQuality = 0
doc.Save(MyDir & "Rendering.SaveToImageJpegQuality0 Out.jpeg", options)

' Try best quality.
options.JpegQuality = 100
doc.Save(MyDir & "Rendering.SaveToImageJpegQuality100 Out.jpeg", options)
Renders a page of a Word document into an image with transparent or coloured background.
[C#]

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

ImageSaveOptions imgOptions = new ImageSaveOptions(SaveFormat.Png);

imgOptions.PaperColor = Color.Transparent;
doc.Save(MyDir + "Rendering.SaveToImagePaperColorTransparent Out.png", imgOptions);

imgOptions.PaperColor = Color.LightCoral;
doc.Save(MyDir + "Rendering.SaveToImagePaperColorCoral Out.png", imgOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim imgOptions As New ImageSaveOptions(SaveFormat.Png)

imgOptions.PaperColor = Color.Transparent
doc.Save(MyDir & "Rendering.SaveToImagePaperColorTransparent Out.png", imgOptions)

imgOptions.PaperColor = Color.LightCoral
doc.Save(MyDir & "Rendering.SaveToImagePaperColorCoral Out.png", imgOptions)
Shows how to render a shape independent of the document to an EMF image and save it to disk.
[C#]

// The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Emf)
{
    Scale = 1.5f
};

// Save the rendered image to disk.
r.Save(dataDir + "TestFile.RenderToDisk Out.emf", imageOptions);
[Visual Basic]

' The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Emf) With {.Scale = 1.5f}

' Save the rendered image to disk.
r.Save(dataDir & "TestFile.RenderToDisk Out.emf", imageOptions)

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 or Jpeg format.

Public Instance Properties

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.
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.
MetafileRenderingOptions | Allows to specify how metafiles are treated in the rendered output.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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 | Gets or sets the 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 or Jpeg.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

Public Instance Methods

Clone Creates a deep clone of this object.

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 or Jpeg format.

[Visual Basic]
Public Sub New( _
ByVal saveFormat As SaveFormat _
)
[C#]
public ImageSaveOptions(
SaveFormat saveFormat
);

Parameters

saveFormat
Can be Tiff, Png, Bmp, Emf or Jpeg.

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(MyDir + "Rendering.JpegDefaultOptions Out.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(MyDir + "Rendering.JpegCustomOptions Out.jpg", imageOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save as a Jpeg image file with default options
doc.Save(MyDir & "Rendering.JpegDefaultOptions Out.jpg")

' Save document to stream as a Jpeg with default options
Dim docStream As 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.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg)
imageOptions.PageIndex = 2
imageOptions.PageCount = 1
imageOptions.JpegQuality = 80
doc.Save(MyDir & "Rendering.JpegCustomOptions Out.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

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.
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.
MetafileRenderingOptions | Allows to specify how metafiles are treated in the rendered output.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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 | Gets or sets the 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 or Jpeg.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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.

Example

Applies LZW compression, saves to color TIFF image with specified brightness and contrast.

[C#]

private static void SaveColorTIFFwithLZW(Document doc, string dataDir, float brightness, float contrast)
{
    // Select the TIFF format with 100 dpi.
    ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff);
    imgOpttiff.Resolution = 100;

    // Select fullcolor LZW compression.
    imgOpttiff.TiffCompression = TiffCompression.Lzw;

    // Set brightness and contrast.
    imgOpttiff.ImageBrightness = brightness;
    imgOpttiff.ImageContrast = contrast;

    // Save multipage color TIFF.
    doc.Save(string.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff);
}
[Visual Basic]

Private Shared Sub SaveColorTIFFwithLZW(ByVal doc As Document, ByVal dataDir As String, ByVal brightness As Single, ByVal contrast As Single)
    ' Select the TIFF format with 100 dpi.
    Dim imgOpttiff As New ImageSaveOptions(SaveFormat.Tiff)
    imgOpttiff.Resolution = 100

    ' Select fullcolor LZW compression.
    imgOpttiff.TiffCompression = TiffCompression.Lzw

    ' Set brightness and contrast.
    imgOpttiff.ImageBrightness = brightness
    imgOpttiff.ImageContrast = contrast

    ' Save multipage color TIFF.
    doc.Save(String.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff)
End Sub
Shows how to render a shape independent of the document to a JPEG image and save it to a stream.
[C#]

// We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
ShapeRenderer r = new ShapeRenderer(shape);

// Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg)
{
    // Output the image in gray scale
    ImageColorMode = ImageColorMode.Grayscale,

    // Reduce the brightness a bit (default is 0.5f).
    ImageBrightness = 0.45f
};

FileStream stream = new FileStream(dataDir + "TestFile.RenderToStream Out.jpg", FileMode.CreateNew);

// Save the rendered image to the stream using different options.
r.Save(stream, imageOptions);
[Visual Basic]

' We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
Dim r As New ShapeRenderer(shape)

' Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
    ' Output the image in gray scale
    ' Reduce the brightness a bit (default is 0.5f).
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg) With {.ImageColorMode = ImageColorMode.Grayscale, .ImageBrightness = 0.45f}

Dim stream As New FileStream(dataDir & "TestFile.RenderToStream Out.jpg", FileMode.CreateNew)

' Save the rendered image to the stream using different options.
r.Save(stream, imageOptions)

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

Shows how to render a shape independent of the document to a JPEG image and save it to a stream.

[C#]

// We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
ShapeRenderer r = new ShapeRenderer(shape);

// Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg)
{
    // Output the image in gray scale
    ImageColorMode = ImageColorMode.Grayscale,

    // Reduce the brightness a bit (default is 0.5f).
    ImageBrightness = 0.45f
};

FileStream stream = new FileStream(dataDir + "TestFile.RenderToStream Out.jpg", FileMode.CreateNew);

// Save the rendered image to the stream using different options.
r.Save(stream, imageOptions);
[Visual Basic]

' We can also retrieve the renderer for a shape by using the ShapeRenderer constructor.
Dim r As New ShapeRenderer(shape)

' Define custom options which control how the image is rendered. Render the shape to the vector format EMF.
    ' Output the image in gray scale
    ' Reduce the brightness a bit (default is 0.5f).
Dim imageOptions As New ImageSaveOptions(SaveFormat.Jpeg) With {.ImageColorMode = ImageColorMode.Grayscale, .ImageBrightness = 0.45f}

Dim stream As New FileStream(dataDir & "TestFile.RenderToStream Out.jpg", FileMode.CreateNew)

' Save the rendered image to the stream using different options.
r.Save(stream, imageOptions)

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.

Example

Applies LZW compression, saves to color TIFF image with specified brightness and contrast.

[C#]

private static void SaveColorTIFFwithLZW(Document doc, string dataDir, float brightness, float contrast)
{
    // Select the TIFF format with 100 dpi.
    ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff);
    imgOpttiff.Resolution = 100;

    // Select fullcolor LZW compression.
    imgOpttiff.TiffCompression = TiffCompression.Lzw;

    // Set brightness and contrast.
    imgOpttiff.ImageBrightness = brightness;
    imgOpttiff.ImageContrast = contrast;

    // Save multipage color TIFF.
    doc.Save(string.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff);
}
[Visual Basic]

Private Shared Sub SaveColorTIFFwithLZW(ByVal doc As Document, ByVal dataDir As String, ByVal brightness As Single, ByVal contrast As Single)
    ' Select the TIFF format with 100 dpi.
    Dim imgOpttiff As New ImageSaveOptions(SaveFormat.Tiff)
    imgOpttiff.Resolution = 100

    ' Select fullcolor LZW compression.
    imgOpttiff.TiffCompression = TiffCompression.Lzw

    ' Set brightness and contrast.
    imgOpttiff.ImageBrightness = brightness
    imgOpttiff.ImageContrast = contrast

    ' Save multipage color TIFF.
    doc.Save(String.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff)
End Sub

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#]
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 options = new ImageSaveOptions(SaveFormat.Jpeg);

// Try worst quality.
options.JpegQuality = 0;
doc.Save(MyDir + "Rendering.SaveToImageJpegQuality0 Out.jpeg", options);

// Try best quality.
options.JpegQuality = 100;
doc.Save(MyDir + "Rendering.SaveToImageJpegQuality100 Out.jpeg", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Jpeg)

' Try worst quality.
options.JpegQuality = 0
doc.Save(MyDir & "Rendering.SaveToImageJpegQuality0 Out.jpeg", options)

' Try best quality.
options.JpegQuality = 100
doc.Save(MyDir & "Rendering.SaveToImageJpegQuality100 Out.jpeg", options)

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#]
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


NumeralFormat Property

Aspose.Words

ImageSaveOptions.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;}

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#]
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);
options.TiffCompression = TiffCompression.Ccitt3;
options.PageIndex = 0;
options.PageCount = 1;

doc.Save(MyDir + "Rendering.SaveToTiffCompression Out.tiff", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Tiff)
options.TiffCompression = TiffCompression.Ccitt3
options.PageIndex = 0
options.PageCount = 1

doc.Save(MyDir & "Rendering.SaveToTiffCompression Out.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#]
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

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);
options.TiffCompression = TiffCompression.Ccitt3;
options.PageIndex = 0;
options.PageCount = 1;

doc.Save(MyDir + "Rendering.SaveToTiffCompression Out.tiff", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Tiff)
options.TiffCompression = TiffCompression.Ccitt3
options.PageIndex = 0
options.PageCount = 1

doc.Save(MyDir & "Rendering.SaveToTiffCompression Out.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 coloured background.

[C#]

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

ImageSaveOptions imgOptions = new ImageSaveOptions(SaveFormat.Png);

imgOptions.PaperColor = Color.Transparent;
doc.Save(MyDir + "Rendering.SaveToImagePaperColorTransparent Out.png", imgOptions);

imgOptions.PaperColor = Color.LightCoral;
doc.Save(MyDir + "Rendering.SaveToImagePaperColorCoral Out.png", imgOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim imgOptions As New ImageSaveOptions(SaveFormat.Png)

imgOptions.PaperColor = Color.Transparent
doc.Save(MyDir & "Rendering.SaveToImagePaperColorTransparent Out.png", imgOptions)

imgOptions.PaperColor = Color.LightCoral
doc.Save(MyDir & "Rendering.SaveToImagePaperColorCoral Out.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+.

See Also

ImageSaveOptions Class | Aspose.Words.Saving Namespace


Resolution Property

Aspose.Words

ImageSaveOptions.Resolution Property

Gets or sets the resolution for the generated images, in dots per inch.

[Visual Basic]
Public Property Resolution As Single
[C#]
public float Resolution {get; set;}

Remarks

This property has effect only when saving to raster image formats.

The default value is 96.

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);
options.Resolution = 300;
options.PageCount = 1;

doc.Save(MyDir + "Rendering.SaveToImageResolution Out.png", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Png)
options.Resolution = 300
options.PageCount = 1

doc.Save(MyDir & "Rendering.SaveToImageResolution Out.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 or Jpeg.

[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.

Example

Shows how to render a shape independent of the document to an EMF image and save it to disk.

[C#]

// The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
// caches the rendered shape.
ShapeRenderer r = shape.GetShapeRenderer();

// Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Emf)
{
    Scale = 1.5f
};

// Save the rendered image to disk.
r.Save(dataDir + "TestFile.RenderToDisk Out.emf", imageOptions);
[Visual Basic]

' The shape render is retrieved using this method. This is made into a separate object from the shape as it internally
' caches the rendered shape.
Dim r As ShapeRenderer = shape.GetShapeRenderer()

' Define custom options which control how the image is rendered. Render the shape to the JPEG raster format.
Dim imageOptions As New ImageSaveOptions(SaveFormat.Emf) With {.Scale = 1.5f}

' Save the rendered image to disk.
r.Save(dataDir & "TestFile.RenderToDisk Out.emf", imageOptions)

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);
options.TiffCompression = TiffCompression.Ccitt3;
options.PageIndex = 0;
options.PageCount = 1;

doc.Save(MyDir + "Rendering.SaveToTiffCompression Out.tiff", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Tiff)
options.TiffCompression = TiffCompression.Ccitt3
options.PageIndex = 0
options.PageCount = 1

doc.Save(MyDir & "Rendering.SaveToTiffCompression Out.tiff", options)

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.

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(MyDir + "Document.SaveWithCustomImagesExport Out.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs e)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (e.ImageFileName.EndsWith(".jpeg"))
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg");
    }
}
[Visual Basic]

Public Sub SaveHtmlExportImages()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Create and pass the object which implements the handler methods.
    Dim options As New HtmlSaveOptions(SaveFormat.Html)
    options.ImageSavingCallback = New HandleImageSaving()

    doc.Save(MyDir & "Document.SaveWithCustomImagesExport Out.html", options)
End Sub

Public Class HandleImageSaving
    Implements IImageSavingCallback
    Private Sub IImageSavingCallback_ImageSaving(ByVal e As ImageSavingArgs) Implements IImageSavingCallback.ImageSaving
        ' Change any images in the document being exported with the extension of "jpeg" to "jpg".
        If e.ImageFileName.EndsWith(".jpeg") Then
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg")
        End If
    End Sub
End Class

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(MyDir + "Document.SaveWithCustomImagesExport Out.html", options);
}

public class HandleImageSaving : IImageSavingCallback
{
    void IImageSavingCallback.ImageSaving(ImageSavingArgs e)
    {
        // Change any images in the document being exported with the extension of "jpeg" to "jpg".
        if (e.ImageFileName.EndsWith(".jpeg"))
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg");
    }
}
[Visual Basic]

Public Sub SaveHtmlExportImages()
    Dim doc As New Document(MyDir & "Document.doc")

    ' Create and pass the object which implements the handler methods.
    Dim options As New HtmlSaveOptions(SaveFormat.Html)
    options.ImageSavingCallback = New HandleImageSaving()

    doc.Save(MyDir & "Document.SaveWithCustomImagesExport Out.html", options)
End Sub

Public Class HandleImageSaving
    Implements IImageSavingCallback
    Private Sub IImageSavingCallback_ImageSaving(ByVal e As ImageSavingArgs) Implements IImageSavingCallback.ImageSaving
        ' Change any images in the document being exported with the extension of "jpeg" to "jpg".
        If e.ImageFileName.EndsWith(".jpeg") Then
            e.ImageFileName = e.ImageFileName.Replace(".jpeg", ".jpg")
        End If
    End Sub
End Class

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


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

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
);

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

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

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.
RenderingMode | Gets or sets a value determining how metafile images should be rendered.
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.
RenderingMode | Gets or sets a value determining how metafile images should be rendered.
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


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.

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

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


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

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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);

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 (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

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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


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

Members

Member Name | Description | Value
Ecma376_2006 | ECMA-376 1st Edition, 2006. | 0
Iso29500_2008_Transitional | ISO/IEC 29500:2008 Transitional compliance level. | 1

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

Compliance | Specifies the OOXML version for the output document. The default value is Ecma376_2006.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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

Compliance | Specifies the OOXML version for the output document. The default value is Ecma376_2006.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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;}

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

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.
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.
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.

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.

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.

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.

See Also

OutlineOptions Class | Aspose.Words.Saving Namespace


PdfCompliance Enumeration

Specifies the PDF standards compliance level.

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

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


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.
X509Certificate2 cert = new X509Certificate2(
    MyDir + "certificate.pfx", "feyb4lgcfbme");

// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(
    cert,
    "Test Signing",
    "Aspose Office",
    DateTime.Now);

// Save the document as PDF with the digital signature set.
doc.Save(MyDir + "Document.Signed Out.pdf", options);
[Visual Basic]

' Create a simple document from scratch.
Dim doc As New Document()
Dim builder As 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.
Dim cert As New X509Certificate2(MyDir & "certificate.pfx", "feyb4lgcfbme")

' Pass the certificate and details to the save options class to sign with.
Dim options As New PdfSaveOptions()
options.DigitalSignatureDetails = New PdfDigitalSignatureDetails(cert, "Test Signing", "Aspose Office", DateTime.Now)

' Save the document as PDF with the digital signature set.
doc.Save(MyDir & "Document.Signed Out.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

Certificate | Gets or sets the certificate to sign with.
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.

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(X509Certificate2,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 (X509Certificate2, String, String, DateTime)

Initializes an instance of this class.

[Visual Basic]
Overloads Public Sub New( _
ByVal certificate As X509Certificate2, _
ByVal reason As String, _
ByVal location As String, _
ByVal signatureDate As Date _
)
[C#]
public PdfDigitalSignatureDetails(
X509Certificate2 certificate,
string reason,
string location,
DateTime signatureDate
);

Parameters

certificate
A certificate to sign with.
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.
X509Certificate2 cert = new X509Certificate2(
    MyDir + "certificate.pfx", "feyb4lgcfbme");

// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(
    cert,
    "Test Signing",
    "Aspose Office",
    DateTime.Now);

// Save the document as PDF with the digital signature set.
doc.Save(MyDir + "Document.Signed Out.pdf", options);
[Visual Basic]

' Create a simple document from scratch.
Dim doc As New Document()
Dim builder As 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.
Dim cert As New X509Certificate2(MyDir & "certificate.pfx", "feyb4lgcfbme")

' Pass the certificate and details to the save options class to sign with.
Dim options As New PdfSaveOptions()
options.DigitalSignatureDetails = New PdfDigitalSignatureDetails(cert, "Test Signing", "Aspose Office", DateTime.Now)

' Save the document as PDF with the digital signature set.
doc.Save(MyDir & "Document.Signed Out.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

Certificate | Gets or sets the certificate to sign with.
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.

See Also

PdfDigitalSignatureDetails Class | Aspose.Words.Saving Namespace | DigitalSignatureDetails


Certificate Property

Aspose.Words

PdfDigitalSignatureDetails.Certificate Property

Gets or sets the certificate to sign with.

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

Remarks

The default value is null. If null, then no signing will be performed.

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


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


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(string.Empty, "password", 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(MyDir + "Rendering.SpecifyPermissions Out.pdf", saveOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim saveOptions As New PdfSaveOptions()

' Create encryption details and set owner password.
Dim encryptionDetails As New PdfEncryptionDetails(String.Empty, "password", PdfEncryptionAlgorithm.RC4_128)

' Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll

' Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations Or PdfPermissions.DocumentAssembly
saveOptions.EncryptionDetails = encryptionDetails

' Render the document to PDF format with the specified permissions.
doc.Save(MyDir & "Rendering.SpecifyPermissions Out.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(string.Empty, "password", 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(MyDir + "Rendering.SpecifyPermissions Out.pdf", saveOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim saveOptions As New PdfSaveOptions()

' Create encryption details and set owner password.
Dim encryptionDetails As New PdfEncryptionDetails(String.Empty, "password", PdfEncryptionAlgorithm.RC4_128)

' Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll

' Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations Or PdfPermissions.DocumentAssembly
saveOptions.EncryptionDetails = encryptionDetails

' Render the document to PDF format with the specified permissions.
doc.Save(MyDir & "Rendering.SpecifyPermissions Out.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(string.Empty, "password", 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(MyDir + "Rendering.SpecifyPermissions Out.pdf", saveOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim saveOptions As New PdfSaveOptions()

' Create encryption details and set owner password.
Dim encryptionDetails As New PdfEncryptionDetails(String.Empty, "password", PdfEncryptionAlgorithm.RC4_128)

' Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll

' Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations Or PdfPermissions.DocumentAssembly
saveOptions.EncryptionDetails = encryptionDetails

' Render the document to PDF format with the specified permissions.
doc.Save(MyDir & "Rendering.SpecifyPermissions Out.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;}

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. If you don't specify an owner password, then the system will generate a random password when generating the PDF document.

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(string.Empty, "password", 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(MyDir + "Rendering.SpecifyPermissions Out.pdf", saveOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim saveOptions As New PdfSaveOptions()

' Create encryption details and set owner password.
Dim encryptionDetails As New PdfEncryptionDetails(String.Empty, "password", PdfEncryptionAlgorithm.RC4_128)

' Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll

' Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations Or PdfPermissions.DocumentAssembly
saveOptions.EncryptionDetails = encryptionDetails

' Render the document to PDF format with the specified permissions.
doc.Save(MyDir & "Rendering.SpecifyPermissions Out.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.

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

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


PdfImageCompression Enumeration

Specifies the type of compression applied to images in the PDF file.

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

Example

Demonstrates how to save images to PDF using JPEG encoding to decrease file size.

[C#]

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

PdfSaveOptions options = new PdfSaveOptions();

// Use JPEG compression at 50% quality to reduce file size.
options.ImageCompression = PdfImageCompression.Jpeg;
options.JpegQuality = 50;

doc.Save(MyDir + "Rendering.JpegImageCompression Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()

' Use JPEG compression at 50% quality to reduce file size.
options.ImageCompression = PdfImageCompression.Jpeg
options.JpegQuality = 50

doc.Save(MyDir & "Rendering.JpegImageCompression Out.pdf", options)

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.

[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(string.Empty, "password", 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(MyDir + "Rendering.SpecifyPermissions Out.pdf", saveOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim saveOptions As New PdfSaveOptions()

' Create encryption details and set owner password.
Dim encryptionDetails As New PdfEncryptionDetails(String.Empty, "password", PdfEncryptionAlgorithm.RC4_128)

' Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll

' Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations Or PdfPermissions.DocumentAssembly
saveOptions.EncryptionDetails = encryptionDetails

' Render the document to PDF format with the specified permissions.
doc.Save(MyDir & "Rendering.SpecifyPermissions Out.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.PdfSaveOptions

[Visual Basic]
Public Class PdfSaveOptions
Inherits SaveOptions
[C#]
public class PdfSaveOptions : SaveOptions

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(MyDir + "Rendering.SaveToPdfNoCompression Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()
options.TextCompression = PdfTextCompression.None

doc.Save(MyDir & "Rendering.SaveToPdfNoCompression Out.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.HeadingsOutlineLevels = 3;
options.ExpandedOutlineLevels = 1;

doc.Save(MyDir + "Rendering.SaveToPdfWithOutline Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()
options.HeadingsOutlineLevels = 3
options.ExpandedOutlineLevels = 1

doc.Save(MyDir & "Rendering.SaveToPdfWithOutline Out.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.
X509Certificate2 cert = new X509Certificate2(
    MyDir + "certificate.pfx", "feyb4lgcfbme");

// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(
    cert,
    "Test Signing",
    "Aspose Office",
    DateTime.Now);

// Save the document as PDF with the digital signature set.
doc.Save(MyDir + "Document.Signed Out.pdf", options);
[Visual Basic]

' Create a simple document from scratch.
Dim doc As New Document()
Dim builder As 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.
Dim cert As New X509Certificate2(MyDir & "certificate.pfx", "feyb4lgcfbme")

' Pass the certificate and details to the save options class to sign with.
Dim options As New PdfSaveOptions()
options.DigitalSignatureDetails = New PdfDigitalSignatureDetails(cert, "Test Signing", "Aspose Office", DateTime.Now)

' Save the document as PDF with the digital signature set.
doc.Save(MyDir & "Document.Signed Out.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

BookmarksOutlineLevel | Obsolete. Specifies the level in the PDF document outline at which to display Word bookmarks.
Compliance | Specifies the PDF standards compliance level for output documents.
DigitalSignatureDetails | Gets or sets the details for signing the output PDF document.
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.
DownsampleImages | Obsolete. Specifies whether or not the images should be downsampled.
DownsampleOptions | Allows to specify downsample options.
DownsampleResolution | Obsolete. Specifies the resolution in pixels per inch to which the images should be downsampled.
EmbedFullFonts | Controls how fonts are embedded into the resulting PDF documents.
EmbedStandardWindowsFonts | Obsolete. Gets or sets a value determining whether or not to embed standard windows fonts Arial and Times New Roman.
EncryptionDetails | Gets or sets the details for encrypting the output PDF document.
ExpandedOutlineLevels | Obsolete. Specifies how many levels in the PDF document outline to show expanded when the PDF file is viewed.
ExportCustomPropertiesAsMetadata | Gets or sets a value determining whether or not to export CustomDocumentProperties as Metadata. The default value is false. When this value is set to true custom document properties are exported in PDF document as 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.
ExportDocumentStructure | Gets or sets a value determining whether or not to export document structure.
FontEmbeddingMode | Specifies the font embedding mode.
HeadingsOutlineLevels | Obsolete. Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the PDF document outline.
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.
MetafileRenderingMode | Obsolete. Gets or sets a value determining how metafile images should be rendered.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | 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.
OutlineOptions | Allows to specify outline options.
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.
PageMode | Specifies how the PDF document should be displayed when opened in the PDF reader.
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.
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 PageSetup.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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.
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.

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(MyDir + "Rendering.EmbedFullFonts Out.pdf");
[Visual Basic]

' Load the document to render.
Dim doc As 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.
Dim options As New PdfSaveOptions()
options.EmbedFullFonts = True

' The output PDF will be embedded with all fonts found in the document.
doc.Save(MyDir & "Rendering.EmbedFullFonts Out.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

BookmarksOutlineLevel | Obsolete. Specifies the level in the PDF document outline at which to display Word bookmarks.
Compliance | Specifies the PDF standards compliance level for output documents.
DigitalSignatureDetails | Gets or sets the details for signing the output PDF document.
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.
DownsampleImages | Obsolete. Specifies whether or not the images should be downsampled.
DownsampleOptions | Allows to specify downsample options.
DownsampleResolution | Obsolete. Specifies the resolution in pixels per inch to which the images should be downsampled.
EmbedFullFonts | Controls how fonts are embedded into the resulting PDF documents.
EmbedStandardWindowsFonts | Obsolete. Gets or sets a value determining whether or not to embed standard windows fonts Arial and Times New Roman.
EncryptionDetails | Gets or sets the details for encrypting the output PDF document.
ExpandedOutlineLevels | Obsolete. Specifies how many levels in the PDF document outline to show expanded when the PDF file is viewed.
ExportCustomPropertiesAsMetadata | Gets or sets a value determining whether or not to export CustomDocumentProperties as Metadata. The default value is false. When this value is set to true custom document properties are exported in PDF document as 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.
ExportDocumentStructure | Gets or sets a value determining whether or not to export document structure.
FontEmbeddingMode | Specifies the font embedding mode.
HeadingsOutlineLevels | Obsolete. Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the PDF document outline.
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.
MetafileRenderingMode | Obsolete. Gets or sets a value determining how metafile images should be rendered.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | 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.
OutlineOptions | Allows to specify outline options.
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.
PageMode | Specifies how the PDF document should be displayed when opened in the PDF reader.
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.
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 PageSetup.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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.
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


BookmarksOutlineLevel Property

Aspose.Words

PdfSaveOptions.BookmarksOutlineLevel Property

NOTE: This property is now obsolete.

Use OutlineOptions.DefaultBookmarksOutlineLevel property.

Specifies the level in the PDF document outline at which to display Word bookmarks.

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

Remarks

Specify 0 and Word bookmarks will not be displayed in the PDF document outline. Specify 1 and Word bookmarks will be displayed in the PDF document outline at level 1; 2 for level 2 and so on.

Default is 0. Valid range is 0 to 9.

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.

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.
X509Certificate2 cert = new X509Certificate2(
    MyDir + "certificate.pfx", "feyb4lgcfbme");

// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(
    cert,
    "Test Signing",
    "Aspose Office",
    DateTime.Now);

// Save the document as PDF with the digital signature set.
doc.Save(MyDir + "Document.Signed Out.pdf", options);
[Visual Basic]

' Create a simple document from scratch.
Dim doc As New Document()
Dim builder As 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.
Dim cert As New X509Certificate2(MyDir & "certificate.pfx", "feyb4lgcfbme")

' Pass the certificate and details to the save options class to sign with.
Dim options As New PdfSaveOptions()
options.DigitalSignatureDetails = New PdfDigitalSignatureDetails(cert, "Test Signing", "Aspose Office", DateTime.Now)

' Save the document as PDF with the digital signature set.
doc.Save(MyDir & "Document.Signed Out.pdf", options)

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


DownsampleImages Property

Aspose.Words

PdfSaveOptions.DownsampleImages Property

NOTE: This property is now obsolete.

Use DownsampleOptions.DownsampleImages property.

Specifies whether or not the 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

PdfSaveOptions Class | Aspose.Words.Saving Namespace


DownsampleOptions Property

Aspose.Words

PdfSaveOptions.DownsampleOptions Property

Allows to specify downsample options.

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

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


DownsampleResolution Property

Aspose.Words

PdfSaveOptions.DownsampleResolution Property

NOTE: This property is now obsolete.

Use DownsampleOptions.Resolution property.

Specifies the resolution in pixels per inch to which the images should be downsampled.

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

Remarks

The default value is 220 ppi.

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(MyDir + "Rendering.EmbedFullFonts Out.pdf");
[Visual Basic]

' Load the document to render.
Dim doc As 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.
Dim options As New PdfSaveOptions()
options.EmbedFullFonts = True

' The output PDF will be embedded with all fonts found in the document.
doc.Save(MyDir & "Rendering.EmbedFullFonts Out.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(MyDir + "Rendering.SubsetFonts Out.pdf");
[Visual Basic]

' Load the document to render.
Dim doc As New Document(MyDir & "Rendering.doc")

' To subset fonts in the output PDF document, simply create new PdfSaveOptions and set EmbedFullFonts to false.
Dim options As 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(MyDir & "Rendering.SubsetFonts Out.pdf")

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


EmbedStandardWindowsFonts Property

Aspose.Words

PdfSaveOptions.EmbedStandardWindowsFonts Property

NOTE: This property is now obsolete.

Use FontEmbeddingMode property.

Gets or sets a value determining whether or not to embed standard windows fonts Arial and Times New Roman.

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

Remarks

The default value is true. When this value is set to false Arial and Times New Roman fonts are not be embedded into PDF.

Only Arial and Times New Roman fonts are affected by this setting because MS Word doesn't embed only these fonts when saving document to the PDF.

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 true 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.EmbedStandardWindowsFonts = false;

// The output PDF will be saved without embedding standard windows fonts.
doc.Save(MyDir + "Rendering.DisableEmbedWindowsFonts Out.pdf");
[Visual Basic]

' Load the document to render.
Dim doc As New Document(MyDir & "Rendering.doc")

' To disable embedding standard windows font use the PdfSaveOptions and set the EmbedStandardWindowsFonts property to false.
Dim options As New PdfSaveOptions()
options.EmbedStandardWindowsFonts = False

' The output PDF will be saved without embedding standard windows fonts.
doc.Save(MyDir & "Rendering.DisableEmbedWindowsFonts Out.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(string.Empty, "password", 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(MyDir + "Rendering.SpecifyPermissions Out.pdf", saveOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim saveOptions As New PdfSaveOptions()

' Create encryption details and set owner password.
Dim encryptionDetails As New PdfEncryptionDetails(String.Empty, "password", PdfEncryptionAlgorithm.RC4_128)

' Start by disallowing all permissions.
encryptionDetails.Permissions = PdfPermissions.DisallowAll

' Extend permissions to allow editing or modifying annotations.
encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations Or PdfPermissions.DocumentAssembly
saveOptions.EncryptionDetails = encryptionDetails

' Render the document to PDF format with the specified permissions.
doc.Save(MyDir & "Rendering.SpecifyPermissions Out.pdf", saveOptions)

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


ExpandedOutlineLevels Property

Aspose.Words

PdfSaveOptions.ExpandedOutlineLevels Property

NOTE: This property is now obsolete.

Use OutlineOptions.ExpandedOutlineLevels property.

Specifies how many levels in the PDF document outline to show expanded when the PDF file is viewed.

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

Remarks

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.HeadingsOutlineLevels = 3;
options.ExpandedOutlineLevels = 1;

doc.Save(MyDir + "Rendering.SaveToPdfWithOutline Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()
options.HeadingsOutlineLevels = 3
options.ExpandedOutlineLevels = 1

doc.Save(MyDir & "Rendering.SaveToPdfWithOutline Out.pdf", options)

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


ExportCustomPropertiesAsMetadata Property

Aspose.Words

PdfSaveOptions.ExportCustomPropertiesAsMetadata Property

Gets or sets a value determining whether or not to export CustomDocumentProperties as Metadata.

The default value is false. When this value is set to true custom document properties are exported in PDF document as 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.

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

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.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


HeadingsOutlineLevels Property

Aspose.Words

PdfSaveOptions.HeadingsOutlineLevels Property

NOTE: This property is now obsolete.

Use OutlineOptions.HeadingsOutlineLevels property.

Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the PDF 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.HeadingsOutlineLevels = 3;
options.ExpandedOutlineLevels = 1;

doc.Save(MyDir + "Rendering.SaveToPdfWithOutline Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()
options.HeadingsOutlineLevels = 3
options.ExpandedOutlineLevels = 1

doc.Save(MyDir & "Rendering.SaveToPdfWithOutline Out.pdf", options)

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

Demonstrates how to save images to PDF using JPEG encoding to decrease file size.

[C#]

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

PdfSaveOptions options = new PdfSaveOptions();

// Use JPEG compression at 50% quality to reduce file size.
options.ImageCompression = PdfImageCompression.Jpeg;
options.JpegQuality = 50;

doc.Save(MyDir + "Rendering.JpegImageCompression Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()

' Use JPEG compression at 50% quality to reduce file size.
options.ImageCompression = PdfImageCompression.Jpeg
options.JpegQuality = 50

doc.Save(MyDir & "Rendering.JpegImageCompression Out.pdf", options)

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#]
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

Demonstrates how to save images to PDF using JPEG encoding to decrease file size.

[C#]

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

PdfSaveOptions options = new PdfSaveOptions();

// Use JPEG compression at 50% quality to reduce file size.
options.ImageCompression = PdfImageCompression.Jpeg;
options.JpegQuality = 50;

doc.Save(MyDir + "Rendering.JpegImageCompression Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()

' Use JPEG compression at 50% quality to reduce file size.
options.ImageCompression = PdfImageCompression.Jpeg
options.JpegQuality = 50

doc.Save(MyDir & "Rendering.JpegImageCompression Out.pdf", options)

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingMode Property

Aspose.Words

PdfSaveOptions.MetafileRenderingMode Property

NOTE: This property is now obsolete.

Use MetafileRenderingOptions.RenderingMode property.

Gets or sets a value determining how metafile images should be rendered.

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

Remarks

Has effect only when a document contains metafile images.

Use this property to get or set the mode of how metafile images inside a document should be rendered when saving in PDF format.

The default value is VectorWithFallback.

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Property

Aspose.Words

PdfSaveOptions.MetafileRenderingOptions Property

Allows to specify metafile rendering options.

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

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Property

Aspose.Words

PdfSaveOptions.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;
[Visual Basic]

Dim options As New PdfSaveOptions()
options.NumeralFormat = NumeralFormat.Context

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.

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


PageCount Property

Aspose.Words

PdfSaveOptions.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(MyDir + "Rendering.SaveToPdfStreamOnePage Out.pdf"))
{
    PdfSaveOptions options = new PdfSaveOptions();
    options.PageIndex = 2;
    options.PageCount = 1;
    doc.Save(stream, options);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Using stream As Stream = File.Create(MyDir & "Rendering.SaveToPdfStreamOnePage Out.pdf")
    Dim options As New PdfSaveOptions()
    options.PageIndex = 2
    options.PageCount = 1
    doc.Save(stream, options)
End Using

See Also

PdfSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

PdfSaveOptions.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(MyDir + "Rendering.SaveToPdfStreamOnePage Out.pdf"))
{
    PdfSaveOptions options = new PdfSaveOptions();
    options.PageIndex = 2;
    options.PageCount = 1;
    doc.Save(stream, options);
}
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Using stream As Stream = File.Create(MyDir & "Rendering.SaveToPdfStreamOnePage Out.pdf")
    Dim options As New PdfSaveOptions()
    options.PageIndex = 2
    options.PageCount = 1
    doc.Save(stream, options)
End Using

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


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(MyDir + "Rendering.PdfDefaultOptions Out.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(MyDir + "Rendering.PdfCustomOptions Out.pdf", pdfOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")

' Option 1: Save document to file in the PDF format with default options
doc.Save(MyDir & "Rendering.PdfDefaultOptions Out.pdf")

' Option 2: Save the document to stream in the PDF format with default options
Dim stream As 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
Dim pdfOptions As New PdfSaveOptions()
pdfOptions.PageIndex = 0
pdfOptions.PageCount = 1
pdfOptions.PreserveFormFields = True
doc.Save(MyDir & "Rendering.PdfCustomOptions Out.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(MyDir + "Rendering.SaveToPdfNoCompression Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()
options.TextCompression = PdfTextCompression.None

doc.Save(MyDir & "Rendering.SaveToPdfNoCompression Out.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 PageSetup.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 subsuite 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 subsuite 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(MyDir + "Rendering.DisableEmbedWindowsFonts Out.pdf");
[Visual Basic]

' Load the document to render.
Dim doc As New Document(MyDir & "Rendering.doc")

' To disable embedding of core fonts and subsuite PDF type 1 fonts set UseCoreFonts to true.
Dim options As New PdfSaveOptions()
options.UseCoreFonts = True

' The output PDF will not be embedded with core fonts such as Arial, Times New Roman etc.
doc.Save(MyDir & "Rendering.DisableEmbedWindowsFonts Out.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.

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(MyDir + "Rendering.SaveToPdfNoCompression Out.pdf", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New PdfSaveOptions()
options.TextCompression = PdfTextCompression.None

doc.Save(MyDir & "Rendering.SaveToPdfNoCompression Out.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.PsSaveOptions

[Visual Basic]
Public Class PsSaveOptions
Inherits SaveOptions
[C#]
public class PsSaveOptions : SaveOptions

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 this class that can be used to save a document in the Ps format.

Public Instance Properties

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 PS document.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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.
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 PageSetup.MultiplePages.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


PsSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Ps format.

[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

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 PS document.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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.
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 PageSetup.MultiplePages.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


JpegQuality Property

Aspose.Words

PsSaveOptions.JpegQuality Property

Gets or sets a value determining the quality of the JPEG images inside PS 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 PS 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

PsSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Property

Aspose.Words

PsSaveOptions.MetafileRenderingOptions Property

Allows to specify metafile rendering options.

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

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Property

Aspose.Words

PsSaveOptions.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;}

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


PageCount Property

Aspose.Words

PsSaveOptions.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;}

See Also

PsSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

PsSaveOptions.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;}

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 PageSetup.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 this class that can be used to save a document in the Rtf format.

Public Instance Properties

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

RtfSaveOptions Class | Aspose.Words.Saving Namespace


RtfSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Rtf format.

[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

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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

DmlEffectsRenderingMode | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode | Gets or sets a value determining how DrawingML shapes are rendered.
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.
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.
WarningCallback | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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

DmlEffectsRenderingMode | Gets or sets a value determining how DrawingML effects are rendered.
DmlRenderingMode | Gets or sets a value determining how DrawingML shapes are rendered.
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.
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.
WarningCallback | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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]
Public Property DmlEffectsRenderingMode As DmlEffectsRenderingMode
[C#]
public 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.

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(MyDir + "Document.PrettyFormat Out.html", htmlOptions);
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

Dim htmlOptions As 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(MyDir & "Document.PrettyFormat Out.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


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. 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.

See Also

SaveOptions Class | Aspose.Words.Saving Namespace


WarningCallback Property

Aspose.Words

SaveOptions.WarningCallback Property

Called during a save 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

Demonstrates 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 procssing. 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);
        }
    }

}
[Visual Basic]

Public Class HandleDocumentWarnings
    Implements IWarningCallback
    ''' <summary>
    ''' Our callback only needs to implement the "Warning" method. This method is called whenever there is a
    ''' potential issue during document procssing. The callback can be set to listen for warnings generated during document
    ''' load and/or document save.
    ''' </summary>
    Public Sub Warning(ByVal info As WarningInfo) Implements IWarningCallback.Warning
        ' We are only interested in fonts being substituted.
        If info.WarningType = WarningType.FontSubstitution Then
            Console.WriteLine("Font substitution: " & info.Description)
        End If
    End Sub

End Class
Demonstrates how to recieve notifications of font substitutions by using IWarningCallback.
[C#]

// Load the document to render.
Document doc = new Document(MyDir + "Document.doc");

// We can choose the default font to use in the case of any missing fonts.
FontSettings.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 subsuited with the default
// font specified under FontSettings.DefaultFontName. We can pick up on this subsuition using our callback.
FontSettings.SetFontsFolder(string.Empty, false);

// Create a new class implementing IWarningCallback which collect any warnings produced during document save.
HandleDocumentWarnings callback = new HandleDocumentWarnings();

// We assign the callback to the appropriate save options class. In this case, we are going to save to PDF
// so we create a PdfSaveOptions class and assign the callback there.
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.WarningCallback = callback;

// Pass the save options along with the save path to the save method.
doc.Save(MyDir + "Rendering.MissingFontNotification Out.pdf", saveOptions);
[Visual Basic]

' Load the document to render.
Dim doc As New Document(MyDir & "Document.doc")

' We can choose the default font to use in the case of any missing fonts.
FontSettings.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 subsuited with the default
' font specified under FontSettings.DefaultFontName. We can pick up on this subsuition using our callback.
FontSettings.SetFontsFolder(String.Empty, False)

' Create a new class implementing IWarningCallback which collect any warnings produced during document save.
Dim callback As New HandleDocumentWarnings()

' We assign the callback to the appropriate save options class. In this case, we are going to save to PDF
' so we create a PdfSaveOptions class and assign the callback there.
Dim saveOptions As New PdfSaveOptions()
saveOptions.WarningCallback = callback

' Pass the save options along with the save path to the save method.
doc.Save(MyDir & "Rendering.MissingFontNotification Out.pdf", saveOptions)

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.SvgSaveOptions

[Visual Basic]
Public Class SvgSaveOptions
Inherits SaveOptions
[C#]
public class SvgSaveOptions : SaveOptions

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 this class that can be used to save a document in the Svg format.

Public Instance Properties

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 | Gets or sets a value determining the quality of the JPEG images inside SVG document.
MetafileRenderingMode | Obsolete. Gets or sets a value determining how metafile images should be rendered.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


SvgSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Svg format.

[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

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 | Gets or sets a value determining the quality of the JPEG images inside SVG document.
MetafileRenderingMode | Obsolete. Gets or sets a value determining how metafile images should be rendered.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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


JpegQuality Property

Aspose.Words

SvgSaveOptions.JpegQuality Property

Gets or sets a value determining the quality of the JPEG images inside SVG 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 SVG 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

SvgSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingMode Property

Aspose.Words

SvgSaveOptions.MetafileRenderingMode Property

NOTE: This property is now obsolete.

Use MetafileRenderingOptions.RenderingMode property.

Gets or sets a value determining how metafile images should be rendered.

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

Remarks

Has effect only when a document contains metafile images.

Use this property to get or set the mode of how metafile images inside a document should be rendered when saving in SVG format.

The default value is VectorWithFallback.

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Property

Aspose.Words

SvgSaveOptions.MetafileRenderingOptions Property

Allows to specify metafile rendering options.

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

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Property

Aspose.Words

SvgSaveOptions.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;}

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


PageCount Property

Aspose.Words

SvgSaveOptions.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;}

See Also

SvgSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

SvgSaveOptions.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;}

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


SwfLeftPaneControlFlags Enumeration

Specifies what buttons are displayed on the left panel of SWF viewer.

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

Members

Member Name | Description | Value
HideAll | Hide all buttons on the left panel of SWF viewer. | 0
ShowAll | Show all buttons in the left panel of SWF viewer. This is the default value. | 1
ShowDocumentMap | Show "Document map" button in the left panel of SWF viewer. | 1

Requirements

Namespace: Aspose.Words.Saving

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

See Also

Aspose.Words.Saving Namespace


SwfSaveOptions Class

Can be used to specify additional options when saving a document into the Swf format.

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

System.Object
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.SwfSaveOptions

[Visual Basic]
Public Class SwfSaveOptions
Inherits SaveOptions
[C#]
public class SwfSaveOptions : SaveOptions

Example

Shows how to specify a custom logo and link it to a web address in the embedded document viewer.

[C#]

// Create an instance of SwfSaveOptions.
SwfSaveOptions options = new SwfSaveOptions();

// Read the image into byte array.
byte[] logoBytes = File.ReadAllBytes(MyDir + "LogoSmall.png");

// Specify the logo image to use.
options.LogoImageBytes = logoBytes;

// You can specify the URL of web page that should be opened when you click on the logo.
options.LogoLink = "http://www.aspose.com";
[Visual Basic]

' Create an instance of SwfSaveOptions.
Dim options As New SwfSaveOptions()

' Read the image into byte array.
Dim logoBytes() As Byte = File.ReadAllBytes(MyDir & "LogoSmall.png")

' Specify the logo image to use.
options.LogoImageBytes = logoBytes

' You can specify the URL of web page that should be opened when you click on the logo.
options.LogoLink = "http://www.aspose.com"
Shows how to change the the tooltips used in the embedded document viewer.
[C#]

// We create an instance of SwfSaveOptions to specify our custom tooltips.
SwfSaveOptions options = new SwfSaveOptions();

// By default, all tooltips are in English. You can specify font used for each tooltip.
// Note that font specified should contain proper glyphs normally used in tooltips.
options.ToolTipsFontName = "Times New Roman";

// The following code will set the tooltip used for each control. In our case we will change the tooltips from English
// to Russian.
options.ToolTips[SwfViewerControlIdentifier.TopPaneActualSizeButton] = "Оригинальный размер";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToHeightButton] = "По высоте страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToWidthButton] = "По ширине страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomOutButton] = "Увеличить";
options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomInButton] = "Уменшить";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSelectionModeButton] = "Режим выделения текста";
options.ToolTips[SwfViewerControlIdentifier.TopPaneDragModeButton] = "Режим перетаскивания";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton] = "Одностнаничный скролинг";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton] = "Одностраничный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton] = "Двустраничный скролинг";
options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton] = "Двустраничный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFullScreenModeButton] = "Полноэкранный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPanePreviousPageButton] = "Предыдущая старница";
options.ToolTips[SwfViewerControlIdentifier.TopPanePageField] = "Введите номер страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneNextPageButton] = "Следующая страница";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchField] = "Введите искомый текст";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchButton] = "Искать";

// Left panel.
options.ToolTips[SwfViewerControlIdentifier.LeftPaneDocumentMapButton] = "Карта документа";
options.ToolTips[SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton] = "Предварительный просмотр страниц";
options.ToolTips[SwfViewerControlIdentifier.LeftPaneAboutButton] = "О приложении";
options.ToolTips[SwfViewerControlIdentifier.LeftPaneCollapsePanelButton] = "Свернуть панель";

// Bottom panel.
options.ToolTips[SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton] = "Показать/Скрыть панель";
[Visual Basic]

' We create an instance of SwfSaveOptions to specify our custom tooltips.
Dim options As New SwfSaveOptions()

' By default, all tooltips are in English. You can specify font used for each tooltip.
' Note that font specified should contain proper glyphs normally used in tooltips.
options.ToolTipsFontName = "Times New Roman"

' The following code will set the tooltip used for each control. In our case we will change the tooltips from English
' to Russian.
options.ToolTips(SwfViewerControlIdentifier.TopPaneActualSizeButton) = "Оригинальный размер"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFitToHeightButton) = "По высоте страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFitToWidthButton) = "По ширине страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneZoomOutButton) = "Увеличить"
options.ToolTips(SwfViewerControlIdentifier.TopPaneZoomInButton) = "Уменшить"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSelectionModeButton) = "Режим выделения текста"
options.ToolTips(SwfViewerControlIdentifier.TopPaneDragModeButton) = "Режим перетаскивания"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton) = "Одностнаничный скролинг"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton) = "Одностраничный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton) = "Двустраничный скролинг"
options.ToolTips(SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton) = "Двустраничный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFullScreenModeButton) = "Полноэкранный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPanePreviousPageButton) = "Предыдущая старница"
options.ToolTips(SwfViewerControlIdentifier.TopPanePageField) = "Введите номер страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneNextPageButton) = "Следующая страница"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSearchField) = "Введите искомый текст"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSearchButton) = "Искать"

' Left panel.
options.ToolTips(SwfViewerControlIdentifier.LeftPaneDocumentMapButton) = "Карта документа"
options.ToolTips(SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton) = "Предварительный просмотр страниц"
options.ToolTips(SwfViewerControlIdentifier.LeftPaneAboutButton) = "О приложении"
options.ToolTips(SwfViewerControlIdentifier.LeftPaneCollapsePanelButton) = "Свернуть панель"

' Bottom panel.
options.ToolTips(SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton) = "Показать/Скрыть панель"

Requirements

Namespace: Aspose.Words.Saving

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

See Also

SwfSaveOptions Members | Aspose.Words.Saving Namespace


SwfSaveOptions Members

SwfSaveOptions overview

Public Instance Constructors

SwfSaveOptions Constructor Initializes a new instance of this class that can be used to save a document in the Swf format.

Public Instance Properties

AllowReadMode | Allows to enable read mode. Can be overridden in flashvars. Default is true.
BookmarksOutlineLevel | Obsolete. Specifies the level in the SWF document outline at which to display Word bookmarks.
Compressed | Specifies whether the generated SWF document should be compressed or not. Default is true.
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.
EnableContextMenu | Enable/disable context menu. Can be overridden in flashvars. Default is true.
ExpandedOutlineLevels | Obsolete. Specifies how many levels in the SWF document outline to show expanded when the SWF file is viewed.
HeadingsOutlineLevels | Obsolete. Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the SWF document outline.
JpegQuality | Gets or sets a value determining the quality of the JPEG images inside SWF document.
LeftPaneControlFlags | Control flags used to configure appearance of left panel of SWF viewer. Default is ShowAll.
LogoImageBytes | Image that will be displayed as logo in the top right corner of the viewer. Image should be 32x64 pixels PNG image, otherwise logo can be displayed improperly.
LogoLink | Gets or sets the full hyperlink address for a logo.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OutlineOptions | Allows to specify outline options.
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.
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 Swf.
ShowBottomPane | Show/hide bottom pane. Can be overridden in flashvars. Default is true.
ShowFullScreen | Show/hide fullscreen button. Can be overridden in flashvars. Default is true.
ShowLeftPane | Show/hide left pane. Can be overridden in flashvars. Default is true.
ShowPageBorder | Specifies whether border around pages should be shown. Default is true.
ShowPageStepper | Show/hide page stepper. Can be overridden in flashvars. Default is true.
ShowSearch | Show/hide search section. Can be overridden in flashvars. Default is true.
ShowTopPane | Show/hide whole top pane. Can be overridden in flashvars. Default is true.
StartOpenLeftPane | Start with opened left pane. Can be overridden in flashvars. Default 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.
ToolTips | Gets or sets tooltips used in SWF viewer. Default is Arial.
ToolTipsFontName | Gets or sets font used for tooltips in SWF viewer. Default is Arial.
TopPaneControlFlags | Control flags used to configure appearance of top panel of SWF viewer. Default is ShowAll.
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.
ViewerIncluded | Specifies whether the generated SWF document should include the integrated document viewer or not. Default is true.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

Public Instance Methods

Clone Creates a deep clone of this object.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


SwfSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Swf format.

[Visual Basic]
Public Sub New()
[C#]
public SwfSaveOptions();

Example

Shows how to specify a custom logo and link it to a web address in the embedded document viewer.

[C#]

// Create an instance of SwfSaveOptions.
SwfSaveOptions options = new SwfSaveOptions();

// Read the image into byte array.
byte[] logoBytes = File.ReadAllBytes(MyDir + "LogoSmall.png");

// Specify the logo image to use.
options.LogoImageBytes = logoBytes;

// You can specify the URL of web page that should be opened when you click on the logo.
options.LogoLink = "http://www.aspose.com";
[Visual Basic]

' Create an instance of SwfSaveOptions.
Dim options As New SwfSaveOptions()

' Read the image into byte array.
Dim logoBytes() As Byte = File.ReadAllBytes(MyDir & "LogoSmall.png")

' Specify the logo image to use.
options.LogoImageBytes = logoBytes

' You can specify the URL of web page that should be opened when you click on the logo.
options.LogoLink = "http://www.aspose.com"

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


SwfSaveOptions Properties

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

Public Instance Properties

AllowReadMode | Allows to enable read mode. Can be overridden in flashvars. Default is true.
BookmarksOutlineLevel | Obsolete. Specifies the level in the SWF document outline at which to display Word bookmarks.
Compressed | Specifies whether the generated SWF document should be compressed or not. Default is true.
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.
EnableContextMenu | Enable/disable context menu. Can be overridden in flashvars. Default is true.
ExpandedOutlineLevels | Obsolete. Specifies how many levels in the SWF document outline to show expanded when the SWF file is viewed.
HeadingsOutlineLevels | Obsolete. Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the SWF document outline.
JpegQuality | Gets or sets a value determining the quality of the JPEG images inside SWF document.
LeftPaneControlFlags | Control flags used to configure appearance of left panel of SWF viewer. Default is ShowAll.
LogoImageBytes | Image that will be displayed as logo in the top right corner of the viewer. Image should be 32x64 pixels PNG image, otherwise logo can be displayed improperly.
LogoLink | Gets or sets the full hyperlink address for a logo.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OutlineOptions | Allows to specify outline options.
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.
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 Swf.
ShowBottomPane | Show/hide bottom pane. Can be overridden in flashvars. Default is true.
ShowFullScreen | Show/hide fullscreen button. Can be overridden in flashvars. Default is true.
ShowLeftPane | Show/hide left pane. Can be overridden in flashvars. Default is true.
ShowPageBorder | Specifies whether border around pages should be shown. Default is true.
ShowPageStepper | Show/hide page stepper. Can be overridden in flashvars. Default is true.
ShowSearch | Show/hide search section. Can be overridden in flashvars. Default is true.
ShowTopPane | Show/hide whole top pane. Can be overridden in flashvars. Default is true.
StartOpenLeftPane | Start with opened left pane. Can be overridden in flashvars. Default 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.
ToolTips | Gets or sets tooltips used in SWF viewer. Default is Arial.
ToolTipsFontName | Gets or sets font used for tooltips in SWF viewer. Default is Arial.
TopPaneControlFlags | Control flags used to configure appearance of top panel of SWF viewer. Default is ShowAll.
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.
ViewerIncluded | Specifies whether the generated SWF document should include the integrated document viewer or not. Default is true.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


AllowReadMode Property

Aspose.Words

SwfSaveOptions.AllowReadMode Property

Allows to enable read mode. Can be overridden in flashvars. Default is true.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevel Property

Aspose.Words

SwfSaveOptions.BookmarksOutlineLevel Property

NOTE: This property is now obsolete.

Use OutlineOptions.DefaultBookmarksOutlineLevel property.

Specifies the level in the SWF document outline at which to display Word bookmarks.

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

Remarks

Specify 0 and Word bookmarks will not be displayed in the SWF document outline. Specify 1 and Word bookmarks will be displayed in the PDF document outline at level 1; 2 for level 2 and so on.

Default is 0. Valid range is 0 to 9.

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


Compressed Property

Aspose.Words

SwfSaveOptions.Compressed Property

Specifies whether the generated SWF document should be compressed or not. Default is true.

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

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


EnableContextMenu Property

Aspose.Words

SwfSaveOptions.EnableContextMenu Property

Enable/disable context menu. Can be overridden in flashvars. Default is true.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ExpandedOutlineLevels Property

Aspose.Words

SwfSaveOptions.ExpandedOutlineLevels Property

NOTE: This property is now obsolete.

Use OutlineOptions.ExpandedOutlineLevels property.

Specifies how many levels in the SWF document outline to show expanded when the SWF file is viewed.

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

Remarks

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.

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


HeadingsOutlineLevels Property

Aspose.Words

SwfSaveOptions.HeadingsOutlineLevels Property

NOTE: This property is now obsolete.

Use OutlineOptions.HeadingsOutlineLevels property.

Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the SWF 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.

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


JpegQuality Property

Aspose.Words

SwfSaveOptions.JpegQuality Property

Gets or sets a value determining the quality of the JPEG images inside SWF 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 SWF 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

SwfSaveOptions Class | Aspose.Words.Saving Namespace


LeftPaneControlFlags Property

Aspose.Words

SwfSaveOptions.LeftPaneControlFlags Property

Control flags used to configure appearance of left panel of SWF viewer. Default is ShowAll.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


LogoImageBytes Property

Aspose.Words

SwfSaveOptions.LogoImageBytes Property

Image that will be displayed as logo in the top right corner of the viewer. Image should be 32x64 pixels PNG image, otherwise logo can be displayed improperly.

[Visual Basic]
Public Property LogoImageBytes As Byte()
[C#]
public byte[] LogoImageBytes {get; set;}

Remarks

Has an effect only if ViewerIncluded is true.

When null no logo is displayed.

Example

Shows how to specify a custom logo and link it to a web address in the embedded document viewer.

[C#]

// Create an instance of SwfSaveOptions.
SwfSaveOptions options = new SwfSaveOptions();

// Read the image into byte array.
byte[] logoBytes = File.ReadAllBytes(MyDir + "LogoSmall.png");

// Specify the logo image to use.
options.LogoImageBytes = logoBytes;

// You can specify the URL of web page that should be opened when you click on the logo.
options.LogoLink = "http://www.aspose.com";
[Visual Basic]

' Create an instance of SwfSaveOptions.
Dim options As New SwfSaveOptions()

' Read the image into byte array.
Dim logoBytes() As Byte = File.ReadAllBytes(MyDir & "LogoSmall.png")

' Specify the logo image to use.
options.LogoImageBytes = logoBytes

' You can specify the URL of web page that should be opened when you click on the logo.
options.LogoLink = "http://www.aspose.com"

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


LogoLink Property

Aspose.Words

SwfSaveOptions.LogoLink Property

Gets or sets the full hyperlink address for a logo.

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

Remarks

Has an effect only if ViewerIncluded is true and LogoImageBytes is specified.

Set to null or empty string to specify no hyperlink.

Example

Shows how to specify a custom logo and link it to a web address in the embedded document viewer.

[C#]

// Create an instance of SwfSaveOptions.
SwfSaveOptions options = new SwfSaveOptions();

// Read the image into byte array.
byte[] logoBytes = File.ReadAllBytes(MyDir + "LogoSmall.png");

// Specify the logo image to use.
options.LogoImageBytes = logoBytes;

// You can specify the URL of web page that should be opened when you click on the logo.
options.LogoLink = "http://www.aspose.com";
[Visual Basic]

' Create an instance of SwfSaveOptions.
Dim options As New SwfSaveOptions()

' Read the image into byte array.
Dim logoBytes() As Byte = File.ReadAllBytes(MyDir & "LogoSmall.png")

' Specify the logo image to use.
options.LogoImageBytes = logoBytes

' You can specify the URL of web page that should be opened when you click on the logo.
options.LogoLink = "http://www.aspose.com"

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Property

Aspose.Words

SwfSaveOptions.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;}

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


OutlineOptions Property

Aspose.Words

SwfSaveOptions.OutlineOptions Property

Allows to specify outline options.

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

Remarks

Note that outline options has effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


PageCount Property

Aspose.Words

SwfSaveOptions.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;}

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

SwfSaveOptions.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;}

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


SaveFormat Property

Aspose.Words

SwfSaveOptions.SaveFormat Property

Specifies the format in which the document will be saved if this save options object is used. Can only be Swf.

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

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ShowBottomPane Property

Aspose.Words

SwfSaveOptions.ShowBottomPane Property

Show/hide bottom pane. Can be overridden in flashvars. Default is true.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ShowFullScreen Property

Aspose.Words

SwfSaveOptions.ShowFullScreen Property

Show/hide fullscreen button. Can be overridden in flashvars. Default is true.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ShowLeftPane Property

Aspose.Words

SwfSaveOptions.ShowLeftPane Property

Show/hide left pane. Can be overridden in flashvars. Default is true.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ShowPageBorder Property

Aspose.Words

SwfSaveOptions.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;}

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ShowPageStepper Property

Aspose.Words

SwfSaveOptions.ShowPageStepper Property

Show/hide page stepper. Can be overridden in flashvars. Default is true.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ShowSearch Property

Aspose.Words

SwfSaveOptions.ShowSearch Property

Show/hide search section. Can be overridden in flashvars. Default is true.

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

Remarks

Has an effect only if ViewerIncluded is true.

Example

Shows how to choose which controls to display in the embedded document viewer.

[C#]

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

// Create an instance of SwfSaveOptions and set some buttons as hidden.
SwfSaveOptions options = new SwfSaveOptions();
// Hide all the buttons with the exception of the page control buttons. Similar flags can be used for the left control pane as well.
options.TopPaneControlFlags = SwfTopPaneControlFlags.HideAll | SwfTopPaneControlFlags.ShowActualSize |
    SwfTopPaneControlFlags.ShowFitToWidth | SwfTopPaneControlFlags.ShowFitToHeight |
    SwfTopPaneControlFlags.ShowZoomIn | SwfTopPaneControlFlags.ShowZoomOut;

// You can also choose to show or hide the main elements of the viewer. Hide the search control.
options.ShowSearch = false;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

' Create an instance of SwfSaveOptions and set some buttons as hidden.
Dim options As New SwfSaveOptions()
' Hide all the buttons with the exception of the page control buttons. Similar flags can be used for the left control pane as well.
options.TopPaneControlFlags = SwfTopPaneControlFlags.HideAll Or SwfTopPaneControlFlags.ShowActualSize Or SwfTopPaneControlFlags.ShowFitToWidth Or SwfTopPaneControlFlags.ShowFitToHeight Or SwfTopPaneControlFlags.ShowZoomIn Or SwfTopPaneControlFlags.ShowZoomOut

' You can also choose to show or hide the main elements of the viewer. Hide the search control.
options.ShowSearch = False

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ShowTopPane Property

Aspose.Words

SwfSaveOptions.ShowTopPane Property

Show/hide whole top pane. Can be overridden in flashvars. Default is true.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


StartOpenLeftPane Property

Aspose.Words

SwfSaveOptions.StartOpenLeftPane Property

Start with opened left pane. Can be overridden in flashvars. Default is false.

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

Remarks

Has an effect only if ViewerIncluded is true.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ToolTips Property

Aspose.Words

SwfSaveOptions.ToolTips Property

Gets or sets tooltips used in SWF viewer. Default is Arial.

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

Remarks

Has an effect only if ViewerIncluded is true.

Example

Shows how to change the the tooltips used in the embedded document viewer.

[C#]

// We create an instance of SwfSaveOptions to specify our custom tooltips.
SwfSaveOptions options = new SwfSaveOptions();

// By default, all tooltips are in English. You can specify font used for each tooltip.
// Note that font specified should contain proper glyphs normally used in tooltips.
options.ToolTipsFontName = "Times New Roman";

// The following code will set the tooltip used for each control. In our case we will change the tooltips from English
// to Russian.
options.ToolTips[SwfViewerControlIdentifier.TopPaneActualSizeButton] = "Оригинальный размер";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToHeightButton] = "По высоте страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToWidthButton] = "По ширине страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomOutButton] = "Увеличить";
options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomInButton] = "Уменшить";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSelectionModeButton] = "Режим выделения текста";
options.ToolTips[SwfViewerControlIdentifier.TopPaneDragModeButton] = "Режим перетаскивания";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton] = "Одностнаничный скролинг";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton] = "Одностраничный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton] = "Двустраничный скролинг";
options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton] = "Двустраничный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFullScreenModeButton] = "Полноэкранный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPanePreviousPageButton] = "Предыдущая старница";
options.ToolTips[SwfViewerControlIdentifier.TopPanePageField] = "Введите номер страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneNextPageButton] = "Следующая страница";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchField] = "Введите искомый текст";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchButton] = "Искать";

// Left panel.
options.ToolTips[SwfViewerControlIdentifier.LeftPaneDocumentMapButton] = "Карта документа";
options.ToolTips[SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton] = "Предварительный просмотр страниц";
options.ToolTips[SwfViewerControlIdentifier.LeftPaneAboutButton] = "О приложении";
options.ToolTips[SwfViewerControlIdentifier.LeftPaneCollapsePanelButton] = "Свернуть панель";

// Bottom panel.
options.ToolTips[SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton] = "Показать/Скрыть панель";
[Visual Basic]

' We create an instance of SwfSaveOptions to specify our custom tooltips.
Dim options As New SwfSaveOptions()

' By default, all tooltips are in English. You can specify font used for each tooltip.
' Note that font specified should contain proper glyphs normally used in tooltips.
options.ToolTipsFontName = "Times New Roman"

' The following code will set the tooltip used for each control. In our case we will change the tooltips from English
' to Russian.
options.ToolTips(SwfViewerControlIdentifier.TopPaneActualSizeButton) = "Оригинальный размер"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFitToHeightButton) = "По высоте страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFitToWidthButton) = "По ширине страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneZoomOutButton) = "Увеличить"
options.ToolTips(SwfViewerControlIdentifier.TopPaneZoomInButton) = "Уменшить"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSelectionModeButton) = "Режим выделения текста"
options.ToolTips(SwfViewerControlIdentifier.TopPaneDragModeButton) = "Режим перетаскивания"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton) = "Одностнаничный скролинг"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton) = "Одностраничный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton) = "Двустраничный скролинг"
options.ToolTips(SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton) = "Двустраничный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFullScreenModeButton) = "Полноэкранный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPanePreviousPageButton) = "Предыдущая старница"
options.ToolTips(SwfViewerControlIdentifier.TopPanePageField) = "Введите номер страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneNextPageButton) = "Следующая страница"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSearchField) = "Введите искомый текст"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSearchButton) = "Искать"

' Left panel.
options.ToolTips(SwfViewerControlIdentifier.LeftPaneDocumentMapButton) = "Карта документа"
options.ToolTips(SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton) = "Предварительный просмотр страниц"
options.ToolTips(SwfViewerControlIdentifier.LeftPaneAboutButton) = "О приложении"
options.ToolTips(SwfViewerControlIdentifier.LeftPaneCollapsePanelButton) = "Свернуть панель"

' Bottom panel.
options.ToolTips(SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton) = "Показать/Скрыть панель"

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ToolTipsFontName Property

Aspose.Words

SwfSaveOptions.ToolTipsFontName Property

Gets or sets font used for tooltips in SWF viewer. Default is Arial.

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

Remarks

If null or empty string is specified, default font is used.

If font is not installed an alternative font is used.

Has an effect only if ViewerIncluded is true.

Example

Shows how to change the the tooltips used in the embedded document viewer.

[C#]

// We create an instance of SwfSaveOptions to specify our custom tooltips.
SwfSaveOptions options = new SwfSaveOptions();

// By default, all tooltips are in English. You can specify font used for each tooltip.
// Note that font specified should contain proper glyphs normally used in tooltips.
options.ToolTipsFontName = "Times New Roman";

// The following code will set the tooltip used for each control. In our case we will change the tooltips from English
// to Russian.
options.ToolTips[SwfViewerControlIdentifier.TopPaneActualSizeButton] = "Оригинальный размер";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToHeightButton] = "По высоте страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToWidthButton] = "По ширине страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomOutButton] = "Увеличить";
options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomInButton] = "Уменшить";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSelectionModeButton] = "Режим выделения текста";
options.ToolTips[SwfViewerControlIdentifier.TopPaneDragModeButton] = "Режим перетаскивания";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton] = "Одностнаничный скролинг";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton] = "Одностраничный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton] = "Двустраничный скролинг";
options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton] = "Двустраничный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFullScreenModeButton] = "Полноэкранный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPanePreviousPageButton] = "Предыдущая старница";
options.ToolTips[SwfViewerControlIdentifier.TopPanePageField] = "Введите номер страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneNextPageButton] = "Следующая страница";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchField] = "Введите искомый текст";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchButton] = "Искать";

// Left panel.
options.ToolTips[SwfViewerControlIdentifier.LeftPaneDocumentMapButton] = "Карта документа";
options.ToolTips[SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton] = "Предварительный просмотр страниц";
options.ToolTips[SwfViewerControlIdentifier.LeftPaneAboutButton] = "О приложении";
options.ToolTips[SwfViewerControlIdentifier.LeftPaneCollapsePanelButton] = "Свернуть панель";

// Bottom panel.
options.ToolTips[SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton] = "Показать/Скрыть панель";
[Visual Basic]

' We create an instance of SwfSaveOptions to specify our custom tooltips.
Dim options As New SwfSaveOptions()

' By default, all tooltips are in English. You can specify font used for each tooltip.
' Note that font specified should contain proper glyphs normally used in tooltips.
options.ToolTipsFontName = "Times New Roman"

' The following code will set the tooltip used for each control. In our case we will change the tooltips from English
' to Russian.
options.ToolTips(SwfViewerControlIdentifier.TopPaneActualSizeButton) = "Оригинальный размер"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFitToHeightButton) = "По высоте страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFitToWidthButton) = "По ширине страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneZoomOutButton) = "Увеличить"
options.ToolTips(SwfViewerControlIdentifier.TopPaneZoomInButton) = "Уменшить"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSelectionModeButton) = "Режим выделения текста"
options.ToolTips(SwfViewerControlIdentifier.TopPaneDragModeButton) = "Режим перетаскивания"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton) = "Одностнаничный скролинг"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton) = "Одностраничный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton) = "Двустраничный скролинг"
options.ToolTips(SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton) = "Двустраничный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFullScreenModeButton) = "Полноэкранный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPanePreviousPageButton) = "Предыдущая старница"
options.ToolTips(SwfViewerControlIdentifier.TopPanePageField) = "Введите номер страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneNextPageButton) = "Следующая страница"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSearchField) = "Введите искомый текст"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSearchButton) = "Искать"

' Left panel.
options.ToolTips(SwfViewerControlIdentifier.LeftPaneDocumentMapButton) = "Карта документа"
options.ToolTips(SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton) = "Предварительный просмотр страниц"
options.ToolTips(SwfViewerControlIdentifier.LeftPaneAboutButton) = "О приложении"
options.ToolTips(SwfViewerControlIdentifier.LeftPaneCollapsePanelButton) = "Свернуть панель"

' Bottom panel.
options.ToolTips(SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton) = "Показать/Скрыть панель"

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


TopPaneControlFlags Property

Aspose.Words

SwfSaveOptions.TopPaneControlFlags Property

Control flags used to configure appearance of top panel of SWF viewer. Default is ShowAll.

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

Remarks

Has an effect only if ViewerIncluded is true.

Example

Shows how to choose which controls to display in the embedded document viewer.

[C#]

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

// Create an instance of SwfSaveOptions and set some buttons as hidden.
SwfSaveOptions options = new SwfSaveOptions();
// Hide all the buttons with the exception of the page control buttons. Similar flags can be used for the left control pane as well.
options.TopPaneControlFlags = SwfTopPaneControlFlags.HideAll | SwfTopPaneControlFlags.ShowActualSize |
    SwfTopPaneControlFlags.ShowFitToWidth | SwfTopPaneControlFlags.ShowFitToHeight |
    SwfTopPaneControlFlags.ShowZoomIn | SwfTopPaneControlFlags.ShowZoomOut;

// You can also choose to show or hide the main elements of the viewer. Hide the search control.
options.ShowSearch = false;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

' Create an instance of SwfSaveOptions and set some buttons as hidden.
Dim options As New SwfSaveOptions()
' Hide all the buttons with the exception of the page control buttons. Similar flags can be used for the left control pane as well.
options.TopPaneControlFlags = SwfTopPaneControlFlags.HideAll Or SwfTopPaneControlFlags.ShowActualSize Or SwfTopPaneControlFlags.ShowFitToWidth Or SwfTopPaneControlFlags.ShowFitToHeight Or SwfTopPaneControlFlags.ShowZoomIn Or SwfTopPaneControlFlags.ShowZoomOut

' You can also choose to show or hide the main elements of the viewer. Hide the search control.
options.ShowSearch = False

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


ViewerIncluded Property

Aspose.Words

SwfSaveOptions.ViewerIncluded Property

Specifies whether the generated SWF document should include the integrated document viewer or not. Default is true.

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

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


SwfSaveOptions Methods

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

Public Instance Methods

Clone Creates a deep clone of this object.

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


SwfSaveOptions.Clone Method

Creates a deep clone of this object.

[Visual Basic]
Public Function Clone() As SwfSaveOptions
[C#]
public SwfSaveOptions Clone();

See Also

SwfSaveOptions Class | Aspose.Words.Saving Namespace


SwfToolTips Class

Allows to specify tooltips displayed in the Aspose.Words SWF Document Viewer.

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

System.Object
Aspose.Words.Saving.SwfToolTips

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

Requirements

Namespace: Aspose.Words.Saving

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

See Also

SwfToolTips Members | Aspose.Words.Saving Namespace


SwfToolTips Members

SwfToolTips overview

Public Instance Properties

Item Gets or sets the tooltip displayed for the specified control.

See Also

SwfToolTips Class | Aspose.Words.Saving Namespace


SwfToolTips Properties

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

Public Instance Properties

Item Gets or sets the tooltip displayed for the specified control.

See Also

SwfToolTips Class | Aspose.Words.Saving Namespace


Item Property

Aspose.Words

SwfToolTips.Item Property

Gets or sets the tooltip displayed for the specified control.

[Visual Basic]
Public Default Property Item( _
ByVal controlIdentifier As SwfViewerControlIdentifier _
) As String
[C#]
public string this[
Aspose.Words.Saving.SwfViewerControlIdentifier controlIdentifier
] {get; set;}

See Also

SwfToolTips Class | Aspose.Words.Saving Namespace


SwfTopPaneControlFlags Enumeration

Specifies what buttons are displayed on the top panel of SWF viewer.

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

Example

Shows how to choose which controls to display in the embedded document viewer.

[C#]

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

// Create an instance of SwfSaveOptions and set some buttons as hidden.
SwfSaveOptions options = new SwfSaveOptions();
// Hide all the buttons with the exception of the page control buttons. Similar flags can be used for the left control pane as well.
options.TopPaneControlFlags = SwfTopPaneControlFlags.HideAll | SwfTopPaneControlFlags.ShowActualSize |
    SwfTopPaneControlFlags.ShowFitToWidth | SwfTopPaneControlFlags.ShowFitToHeight |
    SwfTopPaneControlFlags.ShowZoomIn | SwfTopPaneControlFlags.ShowZoomOut;

// You can also choose to show or hide the main elements of the viewer. Hide the search control.
options.ShowSearch = false;
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")

' Create an instance of SwfSaveOptions and set some buttons as hidden.
Dim options As New SwfSaveOptions()
' Hide all the buttons with the exception of the page control buttons. Similar flags can be used for the left control pane as well.
options.TopPaneControlFlags = SwfTopPaneControlFlags.HideAll Or SwfTopPaneControlFlags.ShowActualSize Or SwfTopPaneControlFlags.ShowFitToWidth Or SwfTopPaneControlFlags.ShowFitToHeight Or SwfTopPaneControlFlags.ShowZoomIn Or SwfTopPaneControlFlags.ShowZoomOut

' You can also choose to show or hide the main elements of the viewer. Hide the search control.
options.ShowSearch = False

Members

Member Name | Description | Value
HideAll | Hide all buttons on the top panel of SWF viewer. | 0
ShowAll | Show all buttons on the top panel of SWF viewer. This is the default value. | 4095
ShowActualSize | Show "Actual size" button on the top panel of SWF viewer. | 1
ShowFitToHeight | Show "Fit to height" button on the top panel of SWF viewer. | 2
ShowFitToWidth | Show "Fit to width" button on the top panel of SWF viewer. | 4
ShowZoomOut | Show "Zoom out" button on the top panel of SWF viewer. | 8
ShowZoomIn | Show "Zoom in" button on the top panel of SWF viewer. | 16
ShowTextSelectionMode | Show "Text section mode" button on the top panel of SWF viewer. | 32
ShowPageDragMode | Show "Page drag mode" button on the top panel of SWF viewer. | 64
ShowSinglePageScroll | Show "Single page scroll" button on the top panel of SWF viewer. | 128
ShowSinglePage | Show "Single page" button on the top panel of SWF viewer. | 256
ShowTwoPagesScroll | Show "Two pages scroll" button on the top panel of SWF viewer. | 512
ShowTwoPages | Show "Two pages" button on the top panel of SWF viewer. | 1024
ShowReadModeButton | Show "Read Mode" button on top panel of SWF viewer. | 2048

Requirements

Namespace: Aspose.Words.Saving

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

See Also

Aspose.Words.Saving Namespace


SwfViewerControlIdentifier Enumeration

Identifies each control in the Aspose.Words SWF Document Viewer.

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

Example

Shows how to change the the tooltips used in the embedded document viewer.

[C#]

// We create an instance of SwfSaveOptions to specify our custom tooltips.
SwfSaveOptions options = new SwfSaveOptions();

// By default, all tooltips are in English. You can specify font used for each tooltip.
// Note that font specified should contain proper glyphs normally used in tooltips.
options.ToolTipsFontName = "Times New Roman";

// The following code will set the tooltip used for each control. In our case we will change the tooltips from English
// to Russian.
options.ToolTips[SwfViewerControlIdentifier.TopPaneActualSizeButton] = "Оригинальный размер";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToHeightButton] = "По высоте страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFitToWidthButton] = "По ширине страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomOutButton] = "Увеличить";
options.ToolTips[SwfViewerControlIdentifier.TopPaneZoomInButton] = "Уменшить";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSelectionModeButton] = "Режим выделения текста";
options.ToolTips[SwfViewerControlIdentifier.TopPaneDragModeButton] = "Режим перетаскивания";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton] = "Одностнаничный скролинг";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton] = "Одностраничный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton] = "Двустраничный скролинг";
options.ToolTips[SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton] = "Двустраничный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPaneFullScreenModeButton] = "Полноэкранный режим";
options.ToolTips[SwfViewerControlIdentifier.TopPanePreviousPageButton] = "Предыдущая старница";
options.ToolTips[SwfViewerControlIdentifier.TopPanePageField] = "Введите номер страницы";
options.ToolTips[SwfViewerControlIdentifier.TopPaneNextPageButton] = "Следующая страница";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchField] = "Введите искомый текст";
options.ToolTips[SwfViewerControlIdentifier.TopPaneSearchButton] = "Искать";

// Left panel.
options.ToolTips[SwfViewerControlIdentifier.LeftPaneDocumentMapButton] = "Карта документа";
options.ToolTips[SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton] = "Предварительный просмотр страниц";
options.ToolTips[SwfViewerControlIdentifier.LeftPaneAboutButton] = "О приложении";
options.ToolTips[SwfViewerControlIdentifier.LeftPaneCollapsePanelButton] = "Свернуть панель";

// Bottom panel.
options.ToolTips[SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton] = "Показать/Скрыть панель";
[Visual Basic]

' We create an instance of SwfSaveOptions to specify our custom tooltips.
Dim options As New SwfSaveOptions()

' By default, all tooltips are in English. You can specify font used for each tooltip.
' Note that font specified should contain proper glyphs normally used in tooltips.
options.ToolTipsFontName = "Times New Roman"

' The following code will set the tooltip used for each control. In our case we will change the tooltips from English
' to Russian.
options.ToolTips(SwfViewerControlIdentifier.TopPaneActualSizeButton) = "Оригинальный размер"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFitToHeightButton) = "По высоте страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFitToWidthButton) = "По ширине страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneZoomOutButton) = "Увеличить"
options.ToolTips(SwfViewerControlIdentifier.TopPaneZoomInButton) = "Уменшить"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSelectionModeButton) = "Режим выделения текста"
options.ToolTips(SwfViewerControlIdentifier.TopPaneDragModeButton) = "Режим перетаскивания"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSinglePageScrollLayoutButton) = "Одностнаничный скролинг"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSinglePageLayoutButton) = "Одностраничный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPaneTwoPageScrollLayoutButton) = "Двустраничный скролинг"
options.ToolTips(SwfViewerControlIdentifier.TopPaneTwoPageLayoutButton) = "Двустраничный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPaneFullScreenModeButton) = "Полноэкранный режим"
options.ToolTips(SwfViewerControlIdentifier.TopPanePreviousPageButton) = "Предыдущая старница"
options.ToolTips(SwfViewerControlIdentifier.TopPanePageField) = "Введите номер страницы"
options.ToolTips(SwfViewerControlIdentifier.TopPaneNextPageButton) = "Следующая страница"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSearchField) = "Введите искомый текст"
options.ToolTips(SwfViewerControlIdentifier.TopPaneSearchButton) = "Искать"

' Left panel.
options.ToolTips(SwfViewerControlIdentifier.LeftPaneDocumentMapButton) = "Карта документа"
options.ToolTips(SwfViewerControlIdentifier.LeftPanePagePreviewPaneButton) = "Предварительный просмотр страниц"
options.ToolTips(SwfViewerControlIdentifier.LeftPaneAboutButton) = "О приложении"
options.ToolTips(SwfViewerControlIdentifier.LeftPaneCollapsePanelButton) = "Свернуть панель"

' Bottom panel.
options.ToolTips(SwfViewerControlIdentifier.BottomPaneShowHideBottomPaneButton) = "Показать/Скрыть панель"

Members

Member Name | Description | Value
TopPaneActualSizeButton | The button that changes the zoom to display the page in actual size. | 0
TopPaneFitToHeightButton | The button that changes the zoom to fit the page into the window height. | 1
TopPaneFitToWidthButton | The button that changes the zoom to fit the page into the window width. | 2
TopPaneZoomOutButton | The bottom that decreases the zoom. | 3
TopPaneZoomInButton | The button that increases the zoom. | 4
TopPaneSelectionModeButton | The button that changes the viewing mode into the text selection mode. | 5
TopPaneDragModeButton | The button that changes the viewing mode into hand dragging mode. | 6
TopPaneSinglePageScrollLayoutButton | The button that switches into the single page scrolling view mode. | 7
TopPaneSinglePageLayoutButton | The button that switches into the single page non-scrolling view mode. | 8
TopPaneTwoPageScrollLayoutButton | The button that switches into the two pages scrolling view mode. | 9
TopPaneTwoPageLayoutButton | The button that switches into the two pages non-scrolling view mode. | 10
TopPaneReadModeButton | The button that switches into the read mode. | 11
TopPaneFullScreenModeButton | The button that switches into the full screen viewing mode. | 12
TopPaneSearchButton | The search button. | 13
TopPaneNextPageButton | The next page button. | 14
TopPanePreviousPageButton | The previous page button. | 15
TopPaneSearchField | The search field. | 16
TopPanePageField | The page number field. | 17
TopPaneCollapsedDropDown | The button that is displayed when the window size is too small to display all buttons. | 18
LeftPaneAboutButton | The about button. | 19
LeftPaneCollapsePanelButton | The button that closes the left navigation pane. | 20
LeftPanePagePreviewPaneButton | The button that displays the page preview pane. | 21
LeftPaneDocumentMapButton | The button that displays the navigation pane. | 22
BottomPaneShowHideBottomPaneButton | The button that shows the system info pane. | 23
ReadModePaneCloseButton | Exit read mode button on read mode pane. | 24
DialogsHelpWindowCloseButton | Close help window button on read mode pane. | 25
DialogsHelpWindow | Help window. | 26

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);
options.TiffCompression = TiffCompression.Ccitt3;
options.PageIndex = 0;
options.PageCount = 1;

doc.Save(MyDir + "Rendering.SaveToTiffCompression Out.tiff", options);
[Visual Basic]

Dim doc As New Document(MyDir & "Rendering.doc")

Dim options As New ImageSaveOptions(SaveFormat.Tiff)
options.TiffCompression = TiffCompression.Ccitt3
options.PageIndex = 0
options.PageCount = 1

doc.Save(MyDir & "Rendering.SaveToTiffCompression Out.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


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.TxtSaveOptions

[Visual Basic]
Public Class TxtSaveOptions
Inherits SaveOptions
[C#]
public class TxtSaveOptions : SaveOptions

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 this class that can be used to save a document in the Text format.

Public Instance Properties

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 plain text format. Default value is Encoding.UTF8.
ExportHeadersFooters | Specifies whether to output headers and footers when exporting in plain text format. Default value is true.
ParagraphBreak | Specifies the string to use as a paragraph break when exporting in plain text format.
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 | 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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


TxtSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the Text format.

[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

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 plain text format. Default value is Encoding.UTF8.
ExportHeadersFooters | Specifies whether to output headers and footers when exporting in plain text format. Default value is true.
ParagraphBreak | Specifies the string to use as a paragraph break when exporting in plain text format.
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 | 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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


Encoding Property

Aspose.Words

TxtSaveOptions.Encoding Property

Specifies the encoding to use when exporting in plain text format. Default value is Encoding.UTF8.

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

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


ExportHeadersFooters Property

Aspose.Words

TxtSaveOptions.ExportHeadersFooters Property

Specifies whether to output headers and footers when exporting in plain text format. Default value is true.

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

Remarks

It is hard to meaningfully output headers and footers to plain text because it is not paginated. When this property is true, Aspose.Words exports only primary headers and footers at the beginning and end of each section. You can disable export of headers and footers altogether by setting this property to false.

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


ParagraphBreak Property

Aspose.Words

TxtSaveOptions.ParagraphBreak Property

Specifies the string to use as a paragraph break when exporting in plain text format.

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

Remarks

The default value is CrLf.

See Also

TxtSaveOptions Class | Aspose.Words.Saving Namespace


PreserveTableLayout Property

Aspose.Words

TxtSaveOptions.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

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


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 this class that can be used to save a document in the WordML format.

Public Instance Properties

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

WordML2003SaveOptions Class | Aspose.Words.Saving Namespace


WordML2003SaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the WordML format.

[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

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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.XamlFixedSaveOptions

[Visual Basic]
Public Class XamlFixedSaveOptions
Inherits SaveOptions
[C#]
public class XamlFixedSaveOptions : SaveOptions

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 this class that can be used to save a document in the XamlFixed format.

Public Instance Properties

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.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


XamlFixedSaveOptions Constructor

Initializes a new instance of this class that can be used to save a document in the XamlFixed format.

[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

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.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Property

Aspose.Words

XamlFixedSaveOptions.MetafileRenderingOptions Property

Allows to specify metafile rendering options.

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

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Property

Aspose.Words

XamlFixedSaveOptions.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;}

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


PageCount Property

Aspose.Words

XamlFixedSaveOptions.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;}

See Also

XamlFixedSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

XamlFixedSaveOptions.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;}

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

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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

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.
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.
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.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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.XpsSaveOptions

[Visual Basic]
Public Class XpsSaveOptions
Inherits SaveOptions
[C#]
public class XpsSaveOptions : SaveOptions

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(MyDir + "Rendering.XpsDefaultOptions Out.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(MyDir + "Rendering.XpsCustomOptions Out.xps", xpsOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save document to file in the Xps format with default options
doc.Save(MyDir & "Rendering.XpsDefaultOptions Out.xps")

' Save document to stream in the Xps format with default options
Dim docStream As 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
Dim xpsOptions As New XpsSaveOptions()
xpsOptions.PageIndex = 0
xpsOptions.PageCount = 1
doc.Save(MyDir & "Rendering.XpsCustomOptions Out.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 Fields

mUseBookFoldPrintingSettings

Public Instance Properties

BookmarksOutlineLevel | Obsolete. Specifies the level in the XPS document outline at which to display Word bookmarks.
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.
HeadingsOutlineLevels | Obsolete. Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the XPS document outline.
MetafileRenderingMode | Obsolete. Gets or sets a value determining how metafile images should be rendered.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OutlineOptions | Allows to specify outline options.
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.
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.
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 PageSetup.MultiplePages.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

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(MyDir + "Rendering.XpsDefaultOptions Out.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(MyDir + "Rendering.XpsCustomOptions Out.xps", xpsOptions);
[Visual Basic]

' Open the document
Dim doc As New Document(MyDir & "Rendering.doc")
' Save document to file in the Xps format with default options
doc.Save(MyDir & "Rendering.XpsDefaultOptions Out.xps")

' Save document to stream in the Xps format with default options
Dim docStream As 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
Dim xpsOptions As New XpsSaveOptions()
xpsOptions.PageIndex = 0
xpsOptions.PageCount = 1
doc.Save(MyDir & "Rendering.XpsCustomOptions Out.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 Fields

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

Public Instance Fields

mUseBookFoldPrintingSettings

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


XpsSaveOptions.mUseBookFoldPrintingSettings Field

[Visual Basic]
Public mUseBookFoldPrintingSettings As Boolean
[C#]
public bool mUseBookFoldPrintingSettings;

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


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

BookmarksOutlineLevel | Obsolete. Specifies the level in the XPS document outline at which to display Word bookmarks.
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.
HeadingsOutlineLevels | Obsolete. Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the XPS document outline.
MetafileRenderingMode | Obsolete. Gets or sets a value determining how metafile images should be rendered.
MetafileRenderingOptions | Allows to specify metafile rendering options.
NumeralFormat | Gets or sets NumeralFormat used for rendering of numerals. European numerals are used by default.
OutlineOptions | Allows to specify outline options.
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.
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.
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 PageSetup.MultiplePages.
UseHighQualityRendering (inherited from SaveOptions) | Gets or sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.
WarningCallback (inherited from SaveOptions) | Called during a save operation, when an issue is detected that might result in data or formatting fidelity loss.

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


BookmarksOutlineLevel Property

Aspose.Words

XpsSaveOptions.BookmarksOutlineLevel Property

NOTE: This property is now obsolete.

Use OutlineOptions.DefaultBookmarksOutlineLevel property.

Specifies the level in the XPS document outline at which to display Word bookmarks.

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

Remarks

Specify 0 and Word bookmarks will not be displayed in the SWF document outline. Specify 1 and Word bookmarks will be displayed in the PDF document outline at level 1; 2 for level 2 and so on.

Default is 0. Valid range is 0 to 9.

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


HeadingsOutlineLevels Property

Aspose.Words

XpsSaveOptions.HeadingsOutlineLevels Property

NOTE: This property is now obsolete.

Use OutlineOptions.HeadingsOutlineLevels property.

Specifies how many levels of headings (paragraphs formatted with the Heading styles) to include in the XPS 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.

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingMode Property

Aspose.Words

XpsSaveOptions.MetafileRenderingMode Property

NOTE: This property is now obsolete.

Use MetafileRenderingOptions.RenderingMode property.

Gets or sets a value determining how metafile images should be rendered.

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

Remarks

Has effect only when a document contains metafile images.

Use this property to get or set the mode of how metafile images inside a document should be rendered when saving in XPS format.

The default value is VectorWithFallback.

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


MetafileRenderingOptions Property

Aspose.Words

XpsSaveOptions.MetafileRenderingOptions Property

Allows to specify metafile rendering options.

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

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


NumeralFormat Property

Aspose.Words

XpsSaveOptions.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;}

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


PageCount Property

Aspose.Words

XpsSaveOptions.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;}

See Also

XpsSaveOptions Class | Aspose.Words.Saving Namespace


PageIndex Property

Aspose.Words

XpsSaveOptions.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;}

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 PageSetup.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).
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.
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.

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;}

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.

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.

[Visual Basic]
Public Sub OptimizeFor( _
ByVal version As MsWordVersion _
)
[C#]
public void OptimizeFor(
MsWordVersion version
);

See Also

CompatibilityOptions 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

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

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 this 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 this 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


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 this 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 this 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 this 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 this 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
[C#]
public class OdsoFieldMapDataCollection : 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 this 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 this 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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.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 this 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 this 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
[C#]
public class OdsoRecipientDataCollection : 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 this 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 this 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 _
Implements IEnumerable.GetEnumerator
[C#]
public IEnumerator GetEnumerator();

Implements

IEnumerable.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(MyDir + "Document.SetZoom Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.ViewOptions.ViewType = ViewType.PageLayout
doc.ViewOptions.ZoomPercent = 50
doc.Save(MyDir & "Document.SetZoom Out.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(MyDir + "Document.SetZoom Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.ViewOptions.ViewType = ViewType.PageLayout
doc.ViewOptions.ZoomPercent = 50
doc.Save(MyDir & "Document.SetZoom Out.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(MyDir + "Document.SetZoom Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.ViewOptions.ViewType = ViewType.PageLayout
doc.ViewOptions.ZoomPercent = 50
doc.Save(MyDir & "Document.SetZoom Out.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(MyDir + "Document.SetZoom Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Document.doc")
doc.ViewOptions.ViewType = ViewType.PageLayout
doc.ViewOptions.ZoomPercent = 50
doc.Save(MyDir & "Document.SetZoom Out.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.

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.

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;}

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;}

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.

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.

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.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.
RowAlignment | Specifies alignment for a table row.
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

Disables autofitting and enables fixed widths for the specified table.

[C#]

// Open the document
Document doc = new Document(dataDir + "TestFile.doc");

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// Disable autofitting on this table.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Save the document to disk.
doc.Save(dataDir + "TestFile.FixedWidth Out.doc");
[Visual Basic]

' Open the document
Dim doc As New Document(dataDir & "TestFile.doc")

Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Disable autofitting on this table.
table.AutoFit(AutoFitBehavior.FixedColumnWidths)

' Save the document to disk.
doc.Save(dataDir & "TestFile.FixedWidth Out.doc")
Autofits a table to fit the page width.
[C#]

// Open the document
Document doc = new Document(dataDir + "TestFile.doc");

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// Autofit the first table to the page width.
table.AutoFit(AutoFitBehavior.AutoFitToWindow);

// Save the document to disk.
doc.Save(dataDir + "TestFile.AutoFitToWindow Out.doc");
[Visual Basic]

' Open the document
Dim doc As New Document(dataDir & "TestFile.doc")

Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Autofit the first table to the page width.
table.AutoFit(AutoFitBehavior.AutoFitToWindow)

' Save the document to disk.
doc.Save(dataDir & "TestFile.AutoFitToWindow Out.doc")
Autofits a table in the document to its contents.
[C#]

// Open the document
Document doc = new Document(dataDir + "TestFile.doc");

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// Auto fit the table to the cell contents
table.AutoFit(AutoFitBehavior.AutoFitToContents);

// Save the document to disk.
doc.Save(dataDir + "TestFile.AutoFitToContents Out.doc");
[Visual Basic]

' Open the document
Dim doc As New Document(dataDir & "TestFile.doc")

Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Auto fit the table to the cell contents
table.AutoFit(AutoFitBehavior.AutoFitToContents)

' Save the document to disk.
doc.Save(dataDir & "TestFile.AutoFitToContents Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "DocumentBuilder.SetTableStyle Out.docx");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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 Or TableStyleOptions.RowBands Or 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(MyDir & "DocumentBuilder.SetTableStyle Out.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);
[Visual Basic]

Dim cellIndex As Integer = 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);

// Replace any instances of our string in the entire table.
table.Range.Replace("Carrots", "Eggs", true, true);
// Replace any instances of our string in the last cell of the table only.
table.LastRow.LastCell.Range.Replace("50", "20", true, true);

doc.Save(MyDir + "Table.ReplaceCellText Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.SimpleTable.doc")

' Get the first table in the document.
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Replace any instances of our string in the entire table.
table.Range.Replace("Carrots", "Eggs", True, True)
' Replace any instances of our string in the last cell of the table only.
table.LastRow.LastCell.Range.Replace("50", "20", True, True)

doc.Save(MyDir & "Table.ReplaceCellText Out.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)
{
    // 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)
    {
        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)
        {
            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();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As 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).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table
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(MyDir + "Table.CreateNestedTable Out.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));
        }
    }

    return table;
}
[Visual Basic]

<Test> _
Public Sub NestedTablesUsingNodeConstructors()
    Dim doc As New Document()

    ' Create the outer table with three rows and four columns.
    Dim outerTable As Table = 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.
    Dim innerTable As Table = CreateTable(doc, 2, 2, "Inner Table")
    ' Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable)

    doc.Save(MyDir & "Table.CreateNestedTable Out.doc")

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, True).Count) ' ExSkip
End Sub

''' <summary>
''' Creates a new table in the document with the given dimensions and text in each cell.
''' </summary>
Private Function CreateTable(ByVal doc As Document, ByVal rowCount As Integer, ByVal cellCount As Integer, ByVal cellText As String) As Table
    Dim table As New Table(doc)

    ' Create the specified number of rows.
    For rowId As Integer = 1 To rowCount
        Dim row As New Row(doc)
        table.AppendChild(row)

        ' Create the specified number of cells for each row.
        For cellId As Integer = 1 To cellCount
            Dim cell As 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))
        Next cellId
    Next rowId

    Return table
End Function
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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.doc")

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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(MyDir + "Table.CreateNestedTable Out.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));
        }
    }

    return table;
}
[Visual Basic]

<Test> _
Public Sub NestedTablesUsingNodeConstructors()
    Dim doc As New Document()

    ' Create the outer table with three rows and four columns.
    Dim outerTable As Table = 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.
    Dim innerTable As Table = CreateTable(doc, 2, 2, "Inner Table")
    ' Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable)

    doc.Save(MyDir & "Table.CreateNestedTable Out.doc")

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, True).Count) ' ExSkip
End Sub

''' <summary>
''' Creates a new table in the document with the given dimensions and text in each cell.
''' </summary>
Private Function CreateTable(ByVal doc As Document, ByVal rowCount As Integer, ByVal cellCount As Integer, ByVal cellText As String) As Table
    Dim table As New Table(doc)

    ' Create the specified number of rows.
    For rowId As Integer = 1 To rowCount
        Dim row As New Row(doc)
        table.AppendChild(row)

        ' Create the specified number of cells for each row.
        For cellId As Integer = 1 To cellCount
            Dim cell As 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))
        Next cellId
    Next rowId

    Return table
End Function

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;
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Retrieve the first cell in the table.
Dim firstCell As Cell = 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(MyDir + "Table.CombineTables Out.doc");
[Visual Basic]

' Load the document.
Dim doc As 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.
Dim firstTable As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
Dim secondTable As Table = CType(doc.GetChild(NodeType.Table, 1, True), Table)

' 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.
Do While secondTable.HasChildNodes
    firstTable.Rows.Add(secondTable.FirstRow)
Loop

' Remove the empty table container.
secondTable.Remove()

doc.Save(MyDir & "Table.CombineTables Out.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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.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(MyDir + "DocumentBuilder.InsertNestedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Build the outer table.
Dim cell As 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(MyDir & "DocumentBuilder.InsertNestedTable Out.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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.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;}

Example

Shows how to merge all the parent cells of an unused region and display a message within the table.

[C#]

// Replace the unused region in the table with a "no records" message and merge all cells into one.
if (args.TableName == "Suppliers")
{
    if ((string)args.FieldValue == "FirstField")
    {
        // We will use the first paragraph to display our message. Make it centered within the table. The other fields in other cells
        // within the table will be merged and won't be displayed so we don't need to do anything else with them.
        parentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Center;
        args.Text = "No records to display";
    }

    // Merge the cells of the table together.
    Cell cell = (Cell)parentParagraph.GetAncestor(NodeType.Cell);
    if (cell != null)
    {
       if (cell.IsFirstCell)
           cell.CellFormat.HorizontalMerge = CellMerge.First; // If this cell is the first cell in the table then the merge is started using "CellMerge.First".
       else
           cell.CellFormat.HorizontalMerge = CellMerge.Previous; // Otherwise the merge is continued using "CellMerge.Previous".
    }
}
[Visual Basic]

' Replace the unused region in the table with a "no records" message and merge all cells into one.
If args.TableName = "Suppliers" Then
    If CStr(args.FieldValue) Is "FirstField" Then
        ' We will use the first paragraph to display our message. Make it centered within the table. The other fields in other cells
        ' within the table will be merged and won't be displayed so we don't need to do anything else with them.
        parentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Center
        args.Text = "No records to display"
    End If

    ' Merge the cells of the table together.
    Dim cell As Cell = CType(parentParagraph.GetAncestor(NodeType.Cell), Cell)
    If cell IsNot Nothing Then
       If cell.IsFirstCell Then
           cell.CellFormat.HorizontalMerge = CellMerge.First ' If this cell is the first cell in the table then the merge is started using "CellMerge.First".
       Else
           cell.CellFormat.HorizontalMerge = CellMerge.Previous ' Otherwise the merge is continued using "CellMerge.Previous".
       End If
    End If
End If

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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))
    foreach (Paragraph para in cell.Paragraphs)
        if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
            para.ParagraphFormat.KeepWithNext = true;
[Visual Basic]

' 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.
For Each cell As Cell In table.GetChildNodes(NodeType.Cell, True)
    For Each para As Paragraph In cell.Paragraphs
        If Not(cell.ParentRow.IsLastRow AndAlso para.IsEndOfCell) Then
            para.ParagraphFormat.KeepWithNext = True
        End If
    Next para
Next cell

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))
    foreach (Paragraph para in cell.Paragraphs)
        if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
            para.ParagraphFormat.KeepWithNext = true;
[Visual Basic]

' 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.
For Each cell As Cell In table.GetChildNodes(NodeType.Cell, True)
    For Each para As Paragraph In cell.Paragraphs
        If Not(cell.ParentRow.IsLastRow AndAlso para.IsEndOfCell) Then
            para.ParagraphFormat.KeepWithNext = True
        End If
    Next para
Next cell

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#]

public void CalcuateDepthOfNestedTables()
{
    Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true))
    {
        // 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)
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells)
        {
            // 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;
}
[Visual Basic]

Public Sub CalcuateDepthOfNestedTables()
    Dim doc As New Document(MyDir & "Table.NestedTables.doc")
    Dim tableIndex As Integer = 0

    For Each table As Table In doc.GetChildNodes(NodeType.Table, True)
        ' First lets find if any cells in the table have tables themselves as children.
        Dim count As Integer = 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.
        Dim tableDepth As Integer = GetNestedDepthOfTable(table)

        If tableDepth > 0 Then
            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)
        End If

        tableIndex += 1
    Next table
End Sub

''' <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 Shared Function GetNestedDepthOfTable(ByVal table As Table) As Integer
    Dim depth As Integer = 0

    Dim type As NodeType = table.NodeType
    ' The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Dim parent As Node = table.GetAncestor(type)

    Do While parent IsNot Nothing
        ' 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 += 1
        parent = parent.GetAncestor(type)
    Loop

    Return depth
End Function

''' <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 Shared Function GetChildTableCount(ByVal table As Table) As Integer
    Dim tableCount As Integer = 0
    ' Iterate through all child rows in the table
    For Each row As Row In table.Rows
        ' Iterate through all child cells in the row
        For Each Cell As Cell In row.Cells
            ' Retrieve the collection of child tables of this cell
            Dim childTables As TableCollection = Cell.Tables

            ' If this cell has a table as a child then return true
            If childTables.Count > 0 Then
                tableCount += 1
            End If
        Next Cell
    Next row

    ' No cell contains a table
    Return tableCount
End Function

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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();
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")

' Gets the first cell in the document.
Dim cell As Cell = CType(doc.GetChild(NodeType.Cell, 0, True), Cell)

' Ensure the cell is valid (the last child is a paragraph).
cell.EnsureMinimum()

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)
{
    // 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)
    {
        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)
        {
            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();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As 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).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table

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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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;
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Retrieve the first cell in the table.
Dim firstCell As Cell = 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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.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 | Returns or sets 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.

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 | Returns or sets 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(MyDir + "Table.CombineTables Out.doc");
[Visual Basic]

' Load the document.
Dim doc As 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.
Dim firstTable As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
Dim secondTable As Table = CType(doc.GetChild(NodeType.Table, 1, True), Table)

' 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.
Do While secondTable.HasChildNodes
    firstTable.Rows.Add(secondTable.FirstRow)
Loop

' Remove the empty table container.
secondTable.Remove()

doc.Save(MyDir & "Table.CombineTables Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.StartTable()
builder.InsertCell()

' Set the cell formatting
Dim cellFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)
    {
        foreach (Cell cell in row.Cells)
        {
            Console.WriteLine(PrintCellMergeType(cell));
        }
    }

}

public string PrintCellMergeType(Cell cell)
{
    bool isHorizontallyMerged = cell.CellFormat.HorizontalMerge != CellMerge.None;
    bool isVerticallyMerged = cell.CellFormat.VerticalMerge != CellMerge.None;
    string cellLocation = string.Format("R{0}, C{1}", cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1, cell.ParentRow.IndexOf(cell) + 1);

    if (isHorizontallyMerged && isVerticallyMerged)
        return string.Format("The cell at {0} is both horizontally and vertically merged", cellLocation);
    else if (isHorizontallyMerged)
        return string.Format("The cell at {0} is horizontally merged.", cellLocation);
    else if (isVerticallyMerged)
        return string.Format("The cell at {0} is vertically merged", cellLocation);
    else
        return string.Format("The cell at {0} is not merged", cellLocation);
}
[Visual Basic]

<Test> _
Public Sub CheckCellsMerged()
    Dim doc As New Document(MyDir & "Table.MergedCells.doc")

    ' Retrieve the first table in the document.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

    For Each row As Row In table.Rows
        For Each cell As Cell In row.Cells
            Console.WriteLine(PrintCellMergeType(cell))
        Next cell
    Next row

End Sub

Public Function PrintCellMergeType(ByVal cell As Cell) As String
    Dim isHorizontallyMerged As Boolean = cell.CellFormat.HorizontalMerge <> CellMerge.None
    Dim isVerticallyMerged As Boolean = cell.CellFormat.VerticalMerge <> CellMerge.None
    Dim cellLocation As String = String.Format("R{0}, C{1}", cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1, cell.ParentRow.IndexOf(cell) + 1)

    If isHorizontallyMerged AndAlso isVerticallyMerged Then
        Return String.Format("The cell at {0} is both horizontally and vertically merged", cellLocation)
    ElseIf isHorizontallyMerged Then
        Return String.Format("The cell at {0} is horizontally merged.", cellLocation)
    ElseIf isVerticallyMerged Then
        Return String.Format("The cell at {0} is vertically merged", cellLocation)
    Else
        Return String.Format("The cell at {0} is not merged", cellLocation)
    End If
End Function

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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.StartTable()
builder.InsertCell()

' Set the cell formatting
Dim cellFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "Table.CellPreferredWidths Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Insert a table row made up of three cells which have different preferred widths.
Dim table As 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(MyDir & "Table.CellPreferredWidths Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.StartTable()
builder.InsertCell()

' Set the cell formatting
Dim cellFormat As 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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.StartTable()
builder.InsertCell()

' Set the cell formatting
Dim cellFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)
    {
        foreach (Cell cell in row.Cells)
        {
            Console.WriteLine(PrintCellMergeType(cell));
        }
    }

}

public string PrintCellMergeType(Cell cell)
{
    bool isHorizontallyMerged = cell.CellFormat.HorizontalMerge != CellMerge.None;
    bool isVerticallyMerged = cell.CellFormat.VerticalMerge != CellMerge.None;
    string cellLocation = string.Format("R{0}, C{1}", cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1, cell.ParentRow.IndexOf(cell) + 1);

    if (isHorizontallyMerged && isVerticallyMerged)
        return string.Format("The cell at {0} is both horizontally and vertically merged", cellLocation);
    else if (isHorizontallyMerged)
        return string.Format("The cell at {0} is horizontally merged.", cellLocation);
    else if (isVerticallyMerged)
        return string.Format("The cell at {0} is vertically merged", cellLocation);
    else
        return string.Format("The cell at {0} is not merged", cellLocation);
}
[Visual Basic]

<Test> _
Public Sub CheckCellsMerged()
    Dim doc As New Document(MyDir & "Table.MergedCells.doc")

    ' Retrieve the first table in the document.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

    For Each row As Row In table.Rows
        For Each cell As Cell In row.Cells
            Console.WriteLine(PrintCellMergeType(cell))
        Next cell
    Next row

End Sub

Public Function PrintCellMergeType(ByVal cell As Cell) As String
    Dim isHorizontallyMerged As Boolean = cell.CellFormat.HorizontalMerge <> CellMerge.None
    Dim isVerticallyMerged As Boolean = cell.CellFormat.VerticalMerge <> CellMerge.None
    Dim cellLocation As String = String.Format("R{0}, C{1}", cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1, cell.ParentRow.IndexOf(cell) + 1)

    If isHorizontallyMerged AndAlso isVerticallyMerged Then
        Return String.Format("The cell at {0} is both horizontally and vertically merged", cellLocation)
    ElseIf isHorizontallyMerged Then
        Return String.Format("The cell at {0} is horizontally merged.", cellLocation)
    ElseIf isVerticallyMerged Then
        Return String.Format("The cell at {0} is vertically merged", cellLocation)
    Else
        Return String.Format("The cell at {0} is not merged", cellLocation)
    End If
End Function

See Also

CellFormat Class | Aspose.Words.Tables Namespace | HorizontalMerge


Width Property

Aspose.Words

CellFormat.Width Property

Returns or sets the width of the cell in points.

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

Remarks

When the parent table's Auto Fit option is disabled, then this property specifies the actual width of the cell. but when the parent table's Auto Fit option is enabled, then this width can be updated by the table layout algorithm according to PreferredWidth of this cell and other factors.

The default value is 0. The value of 0 is acceptable while the document is in memory, but it is never written to a file. When saving to a file, Aspose.Words invokes it's table layout algorithm to update cell widths if it encounters zero cell widths.

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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

builder.StartTable()
builder.InsertCell()

' Set the cell formatting
Dim cellFormat As 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.

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(MyDir + "Table.CombineTables Out.doc");
[Visual Basic]

' Load the document.
Dim doc As 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.
Dim firstTable As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
Dim secondTable As Table = CType(doc.GetChild(NodeType.Table, 1, True), Table)

' 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.
Do While secondTable.HasChildNodes
    firstTable.Rows.Add(secondTable.FirstRow)
Loop

' Remove the empty table container.
secondTable.Remove()

doc.Save(MyDir & "Table.CombineTables Out.doc")

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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As 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)
    {
        foreach (Cell cell in row.Cells)
        {
            Console.WriteLine(PrintCellMergeType(cell));
        }
    }

}

public string PrintCellMergeType(Cell cell)
{
    bool isHorizontallyMerged = cell.CellFormat.HorizontalMerge != CellMerge.None;
    bool isVerticallyMerged = cell.CellFormat.VerticalMerge != CellMerge.None;
    string cellLocation = string.Format("R{0}, C{1}", cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1, cell.ParentRow.IndexOf(cell) + 1);

    if (isHorizontallyMerged && isVerticallyMerged)
        return string.Format("The cell at {0} is both horizontally and vertically merged", cellLocation);
    else if (isHorizontallyMerged)
        return string.Format("The cell at {0} is horizontally merged.", cellLocation);
    else if (isVerticallyMerged)
        return string.Format("The cell at {0} is vertically merged", cellLocation);
    else
        return string.Format("The cell at {0} is not merged", cellLocation);
}
[Visual Basic]

<Test> _
Public Sub CheckCellsMerged()
    Dim doc As New Document(MyDir & "Table.MergedCells.doc")

    ' Retrieve the first table in the document.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

    For Each row As Row In table.Rows
        For Each cell As Cell In row.Cells
            Console.WriteLine(PrintCellMergeType(cell))
        Next cell
    Next row

End Sub

Public Function PrintCellMergeType(ByVal cell As Cell) As String
    Dim isHorizontallyMerged As Boolean = cell.CellFormat.HorizontalMerge <> CellMerge.None
    Dim isVerticallyMerged As Boolean = cell.CellFormat.VerticalMerge <> CellMerge.None
    Dim cellLocation As String = String.Format("R{0}, C{1}", cell.ParentRow.ParentTable.IndexOf(cell.ParentRow) + 1, cell.ParentRow.IndexOf(cell) + 1)

    If isHorizontallyMerged AndAlso isVerticallyMerged Then
        Return String.Format("The cell at {0} is both horizontally and vertically merged", cellLocation)
    ElseIf isHorizontallyMerged Then
        Return String.Format("The cell at {0} is horizontally merged.", cellLocation)
    ElseIf isVerticallyMerged Then
        Return String.Format("The cell at {0} is vertically merged", cellLocation)
    Else
        Return String.Format("The cell at {0} is not merged", cellLocation)
    End If
End Function

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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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]
Public Class PreferredWidth
[C#]
public 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(MyDir + "Table.PreferredWidth Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Insert a table with a width that takes up half the page width.
Dim table As 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(MyDir & "Table.PreferredWidth Out.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(MyDir + "Table.CellPreferredWidths Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Insert a table row made up of three cells which have different preferred widths.
Dim table As 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(MyDir & "Table.CellPreferredWidths Out.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(MyDir + "Table.CellPreferredWidths Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Insert a table row made up of three cells which have different preferred widths.
Dim table As 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(MyDir & "Table.CellPreferredWidths Out.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;
[Visual Basic]

Dim firstCell As Cell = table.FirstRow.FirstCell
Dim type As PreferredWidthType = firstCell.CellFormat.PreferredWidth.Type
Dim value As Double = 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;
[Visual Basic]

Dim firstCell As Cell = table.FirstRow.FirstCell
Dim type As PreferredWidthType = firstCell.CellFormat.PreferredWidth.Type
Dim value As Double = 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(MyDir + "Table.PreferredWidth Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Insert a table with a width that takes up half the page width.
Dim table As 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(MyDir & "Table.PreferredWidth Out.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(MyDir + "Table.CellPreferredWidths Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Insert a table row made up of three cells which have different preferred widths.
Dim table As 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(MyDir & "Table.CellPreferredWidths Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "Table.CellPreferredWidths Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Insert a table row made up of three cells which have different preferred widths.
Dim table As 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(MyDir & "Table.CellPreferredWidths Out.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;
[Visual Basic]

Dim firstCell As Cell = table.FirstRow.FirstCell
Dim type As PreferredWidthType = firstCell.CellFormat.PreferredWidth.Type
Dim value As Double = 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);
[Visual Basic]

Dim rowIndex As Integer = 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)
    cell.RemoveAllChildren();

// Add the row to the end of the table.
table.AppendChild(clonedRow);

doc.Save(MyDir + "Table.AddCloneRowToTable Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.SimpleTable.doc")

' Retrieve the first table in the document.
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Clone the last row in the table.
Dim clonedRow As Row = CType(table.LastRow.Clone(True), Row)

' Remove all content from the cloned row's cells. This makes the row ready for
' new content to be inserted into.
For Each cell As Cell In clonedRow.Cells
    cell.RemoveAllChildren()
Next cell

' Add the row to the end of the table.
table.AppendChild(clonedRow)

doc.Save(MyDir & "Table.AddCloneRowToTable Out.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)
{
    // 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)
    {
        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)
        {
            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();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As 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).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table
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(MyDir + "Table.CreateNestedTable Out.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));
        }
    }

    return table;
}
[Visual Basic]

<Test> _
Public Sub NestedTablesUsingNodeConstructors()
    Dim doc As New Document()

    ' Create the outer table with three rows and four columns.
    Dim outerTable As Table = 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.
    Dim innerTable As Table = CreateTable(doc, 2, 2, "Inner Table")
    ' Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable)

    doc.Save(MyDir & "Table.CreateNestedTable Out.doc")

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, True).Count) ' ExSkip
End Sub

''' <summary>
''' Creates a new table in the document with the given dimensions and text in each cell.
''' </summary>
Private Function CreateTable(ByVal doc As Document, ByVal rowCount As Integer, ByVal cellCount As Integer, ByVal cellText As String) As Table
    Dim table As New Table(doc)

    ' Create the specified number of rows.
    For rowId As Integer = 1 To rowCount
        Dim row As New Row(doc)
        table.AppendChild(row)

        ' Create the specified number of cells for each row.
        For cellId As Integer = 1 To cellCount
            Dim cell As 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))
        Next cellId
    Next rowId

    Return table
End Function
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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.doc")

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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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(MyDir + "Table.CreateNestedTable Out.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));
        }
    }

    return table;
}
[Visual Basic]

<Test> _
Public Sub NestedTablesUsingNodeConstructors()
    Dim doc As New Document()

    ' Create the outer table with three rows and four columns.
    Dim outerTable As Table = 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.
    Dim innerTable As Table = CreateTable(doc, 2, 2, "Inner Table")
    ' Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable)

    doc.Save(MyDir & "Table.CreateNestedTable Out.doc")

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, True).Count) ' ExSkip
End Sub

''' <summary>
''' Creates a new table in the document with the given dimensions and text in each cell.
''' </summary>
Private Function CreateTable(ByVal doc As Document, ByVal rowCount As Integer, ByVal cellCount As Integer, ByVal cellText As String) As Table
    Dim table As New Table(doc)

    ' Create the specified number of rows.
    For rowId As Integer = 1 To rowCount
        Dim row As New Row(doc)
        table.AppendChild(row)

        ' Create the specified number of cells for each row.
        For cellId As Integer = 1 To cellCount
            Dim cell As 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))
        Next cellId
    Next rowId

    Return table
End Function

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)
{
    // 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)
    {
        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)
        {
            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();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As 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).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table

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))
    foreach (Paragraph para in cell.Paragraphs)
        if (!(cell.ParentRow.IsLastRow && para.IsEndOfCell))
            para.ParagraphFormat.KeepWithNext = true;
[Visual Basic]

' 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.
For Each cell As Cell In table.GetChildNodes(NodeType.Cell, True)
    For Each para As Paragraph In cell.Paragraphs
        If Not(cell.ParentRow.IsLastRow AndAlso para.IsEndOfCell) Then
            para.ParagraphFormat.KeepWithNext = True
        End If
    Next para
Next cell

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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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;
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Retrieve the first row in the table.
Dim firstRow As Row = 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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.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) | Creates a duplicate of the 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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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();
[Visual Basic]

Dim doc As New Document()

' Create a new table and add it to the document.
Dim table As New Table(doc)
doc.FirstSection.Body.AppendChild(table)

' Create a new row and add it to the table.
Dim row As 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


RowAlignment Enumeration

Specifies alignment for a table row.

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

Members

Member Name | Description | Value
Left | The row is aligned to the left. | 0
Center | The row is centered. | 1
Right | The row is aligned to the right. | 2

Requirements

Namespace: Aspose.Words.Tables

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

See Also

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)
{
    // 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)
    {
        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)
        {
            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();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As 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).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table

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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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;
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Retrieve the first row in the table.
Dim firstRow As Row = 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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.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

Alignment | Obsolete. Gets or sets a value that represents the alignment for the row.
AllowAutoFit | Obsolete. Allows Microsoft Word to automatically resize cells in a table to fit their contents.
AllowBreakAcrossPages | True if the text in a table row is allowed to split across a page break.
Bidi | Obsolete. Gets or sets whether this is a right-to-left table.
Borders | Gets the collection of default cell borders for the row.
BottomPadding | Obsolete. Gets or sets the amount of space (in points) to add below the contents of cells.
CellSpacing | Obsolete. Gets or sets the amount of space (in points) between the cells.
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.
LeftIndent | Obsolete. Gets or sets the value that represents the left indent of the table row.
LeftPadding | Obsolete. Gets or sets the amount of space (in points) to add to the left of the contents of cells.
PreferredWidth | Obsolete. Gets or sets the preferred table width.
RightPadding | Obsolete. Gets or sets the amount of space (in points) to add to the right of the contents of cells.
TopPadding | Obsolete. Gets or sets the amount of space (in points) to add above the contents of cells.

Public Instance Methods

ClearCellPadding | Obsolete. Sets default cell margins (padding) to zero.
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

Alignment | Obsolete. Gets or sets a value that represents the alignment for the row.
AllowAutoFit | Obsolete. Allows Microsoft Word to automatically resize cells in a table to fit their contents.
AllowBreakAcrossPages | True if the text in a table row is allowed to split across a page break.
Bidi | Obsolete. Gets or sets whether this is a right-to-left table.
Borders | Gets the collection of default cell borders for the row.
BottomPadding | Obsolete. Gets or sets the amount of space (in points) to add below the contents of cells.
CellSpacing | Obsolete. Gets or sets the amount of space (in points) between the cells.
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.
LeftIndent | Obsolete. Gets or sets the value that represents the left indent of the table row.
LeftPadding | Obsolete. Gets or sets the amount of space (in points) to add to the left of the contents of cells.
PreferredWidth | Obsolete. Gets or sets the preferred table width.
RightPadding | Obsolete. Gets or sets the amount of space (in points) to add to the right of the contents of cells.
TopPadding | Obsolete. Gets or sets the amount of space (in points) to add above the contents of cells.

See Also

RowFormat Class | Aspose.Words.Tables Namespace


Alignment Property

Aspose.Words

RowFormat.Alignment Property

NOTE: This property is now obsolete.

Use Table.Alignment instead.

Gets or sets a value that represents the alignment for the row.

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

See Also

RowFormat Class | Aspose.Words.Tables Namespace


AllowAutoFit Property

Aspose.Words

RowFormat.AllowAutoFit Property

NOTE: This property is now obsolete.

Use Table.AllowAutoFit instead.

Allows Microsoft Word to automatically resize cells in a table to fit their contents.

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

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)
    row.RowFormat.AllowBreakAcrossPages = false;
[Visual Basic]

' Disable breaking across pages for all rows in the table.
For Each row As Row In table
    row.RowFormat.AllowBreakAcrossPages = False
Next row

See Also

RowFormat Class | Aspose.Words.Tables Namespace


Bidi Property

Aspose.Words

RowFormat.Bidi Property

NOTE: This property is now obsolete.

Use Table.Bidi instead.

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.

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


BottomPadding Property

Aspose.Words

RowFormat.BottomPadding Property

NOTE: This property is now obsolete.

Use Table.BottomPadding instead.

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;}

See Also

RowFormat Class | Aspose.Words.Tables Namespace


CellSpacing Property

Aspose.Words

RowFormat.CellSpacing Property

NOTE: This property is now obsolete.

Use Table.CellSpacing instead.

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

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(MyDir + "Table.HeadingRow Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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 i As Integer = 0 To 49
    builder.InsertCell()
    builder.RowFormat.HeadingFormat = False
    builder.Write("Column 1 Text")
    builder.InsertCell()
    builder.Write("Column 2 Text")
    builder.EndRow()
Next i

doc.Save(MyDir & "Table.HeadingRow Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As Table = builder.StartTable()
builder.InsertCell()

' Set the row formatting
Dim rowFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As Table = builder.StartTable()
builder.InsertCell()

' Set the row formatting
Dim rowFormat As 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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.doc")

See Also

RowFormat Class | Aspose.Words.Tables Namespace


LeftIndent Property

Aspose.Words

RowFormat.LeftIndent Property

NOTE: This property is now obsolete.

Use Table.LeftIndent instead.

Gets or sets the value that represents the left indent of the table row.

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

See Also

RowFormat Class | Aspose.Words.Tables Namespace


LeftPadding Property

Aspose.Words

RowFormat.LeftPadding Property

NOTE: This property is now obsolete.

Use Table.LeftPadding instead.

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;}

See Also

RowFormat Class | Aspose.Words.Tables Namespace


PreferredWidth Property

Aspose.Words

RowFormat.PreferredWidth Property

NOTE: This property is now obsolete.

Use Table.PreferredWidth instead.

Gets or sets the preferred table width.

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

See Also

RowFormat Class | Aspose.Words.Tables Namespace


RightPadding Property

Aspose.Words

RowFormat.RightPadding Property

NOTE: This property is now obsolete.

Use Table.RightPadding instead.

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;}

See Also

RowFormat Class | Aspose.Words.Tables Namespace


TopPadding Property

Aspose.Words

RowFormat.TopPadding Property

NOTE: This property is now obsolete.

Use Table.TopPadding instead.

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;}

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

ClearCellPadding | Obsolete. Sets default cell margins (padding) to zero.
ClearFormatting | Resets to default row formatting.

See Also

RowFormat Class | Aspose.Words.Tables Namespace


RowFormat.ClearCellPadding Method

NOTE: This method is now obsolete.

Use padding properties on the Table instead.

Sets default cell margins (padding) to zero.

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

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(MyDir + "Table.ClearBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")

' Remove all borders from the first table in the document.
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Clear the borders all cells in the table.
table.ClearBorders()

doc.Save(MyDir & "Table.ClearBorders Out.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(MyDir + "Table.CombineTables Out.doc");
[Visual Basic]

' Load the document.
Dim doc As 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.
Dim firstTable As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
Dim secondTable As Table = CType(doc.GetChild(NodeType.Table, 1, True), Table)

' 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.
Do While secondTable.HasChildNodes
    firstTable.Rows.Add(secondTable.FirstRow)
Loop

' Remove the empty table container.
secondTable.Remove()

doc.Save(MyDir & "Table.CombineTables Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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)
{
    // 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)
    {
        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)
        {
            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();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As 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).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table
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(MyDir + "Table.CreateNestedTable Out.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));
        }
    }

    return table;
}
[Visual Basic]

<Test> _
Public Sub NestedTablesUsingNodeConstructors()
    Dim doc As New Document()

    ' Create the outer table with three rows and four columns.
    Dim outerTable As Table = 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.
    Dim innerTable As Table = CreateTable(doc, 2, 2, "Inner Table")
    ' Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable)

    doc.Save(MyDir & "Table.CreateNestedTable Out.doc")

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, True).Count) ' ExSkip
End Sub

''' <summary>
''' Creates a new table in the document with the given dimensions and text in each cell.
''' </summary>
Private Function CreateTable(ByVal doc As Document, ByVal rowCount As Integer, ByVal cellCount As Integer, ByVal cellText As String) As Table
    Dim table As New Table(doc)

    ' Create the specified number of rows.
    For rowId As Integer = 1 To rowCount
        Dim row As New Row(doc)
        table.AppendChild(row)

        ' Create the specified number of cells for each row.
        For cellId As Integer = 1 To cellCount
            Dim cell As 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))
        Next cellId
    Next rowId

    Return table
End Function
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 algorthim 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"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As 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 algorthim for example.
Dim row As 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
Dim cell As 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"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.doc")

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

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.
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.
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.
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.
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 | Get or sets TextWrapping TextWrapping for table.
TopPadding | Gets or sets the amount of space (in points) to add above the contents of cells.

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) | Creates a duplicate of the node.
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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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(MyDir + "Table.CreateNestedTable Out.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));
        }
    }

    return table;
}
[Visual Basic]

<Test> _
Public Sub NestedTablesUsingNodeConstructors()
    Dim doc As New Document()

    ' Create the outer table with three rows and four columns.
    Dim outerTable As Table = 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.
    Dim innerTable As Table = CreateTable(doc, 2, 2, "Inner Table")
    ' Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable)

    doc.Save(MyDir & "Table.CreateNestedTable Out.doc")

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, True).Count) ' ExSkip
End Sub

''' <summary>
''' Creates a new table in the document with the given dimensions and text in each cell.
''' </summary>
Private Function CreateTable(ByVal doc As Document, ByVal rowCount As Integer, ByVal cellCount As Integer, ByVal cellText As String) As Table
    Dim table As New Table(doc)

    ' Create the specified number of rows.
    For rowId As Integer = 1 To rowCount
        Dim row As New Row(doc)
        table.AppendChild(row)

        ' Create the specified number of cells for each row.
        For cellId As Integer = 1 To cellCount
            Dim cell As 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))
        Next cellId
    Next rowId

    Return table
End Function

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

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.
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.
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.
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.
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 | Get or sets TextWrapping TextWrapping for table.
TopPadding | Gets or sets the amount of space (in points) to add above the contents of cells.

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(MyDir + "Table.SetOutlineBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.EmptyTable.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' 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(MyDir & "Table.SetOutlineBorders Out.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;
[Visual Basic]

table.AllowAutoFit = True

See Also

Table Class | Aspose.Words.Tables Namespace | AutoFit


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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As Table = builder.StartTable()
builder.InsertCell()

' Set the row formatting
Dim rowFormat As 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


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)
{
    // Quick typed access to the first row of the table.
    if (table.FirstRow != null)
        table.FirstRow.Remove();

    // Quick typed access to the last row of the table.
    if (table.LastRow != null)
        table.LastRow.Remove();
}
[Visual Basic]

' Quick typed access to the first child Section node of the Document.
Dim section As Section = doc.FirstSection

' Quick typed access to the Body child node of the Section.
Dim body As Body = section.Body

' Quick typed access to all Table child nodes contained in the Body.
Dim tables As TableCollection = body.Tables

For Each table As Table In tables
    ' Quick typed access to the first row of the table.
    If table.FirstRow IsNot Nothing Then
        table.FirstRow.Remove()
    End If

    ' Quick typed access to the last row of the table.
    If table.LastRow IsNot Nothing Then
        table.LastRow.Remove()
    End If
Next table
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(MyDir + "Table.CombineTables Out.doc");
[Visual Basic]

' Load the document.
Dim doc As 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.
Dim firstTable As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
Dim secondTable As Table = CType(doc.GetChild(NodeType.Table, 1, True), Table)

' 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.
Do While secondTable.HasChildNodes
    firstTable.Rows.Add(secondTable.FirstRow)
Loop

' Remove the empty table container.
secondTable.Remove()

doc.Save(MyDir & "Table.CombineTables Out.doc")

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)
{
    // Quick typed access to the first row of the table.
    if (table.FirstRow != null)
        table.FirstRow.Remove();

    // Quick typed access to the last row of the table.
    if (table.LastRow != null)
        table.LastRow.Remove();
}
[Visual Basic]

' Quick typed access to the first child Section node of the Document.
Dim section As Section = doc.FirstSection

' Quick typed access to the Body child node of the Section.
Dim body As Body = section.Body

' Quick typed access to all Table child nodes contained in the Body.
Dim tables As TableCollection = body.Tables

For Each table As Table In tables
    ' Quick typed access to the first row of the table.
    If table.FirstRow IsNot Nothing Then
        table.FirstRow.Remove()
    End If

    ' Quick typed access to the last row of the table.
    If table.LastRow IsNot Nothing Then
        table.LastRow.Remove()
    End If
Next table

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(MyDir + "DocumentBuilder.CreateFormattedTable Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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," & Constants.vbLf & " 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," & Constants.vbLf & " Cell 2")

builder.InsertCell()
builder.CellFormat.Width = 200.0
builder.Write("Header Row," & Constants.vbLf & " 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(MyDir & "DocumentBuilder.CreateFormattedTable Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As Table = builder.StartTable()
builder.InsertCell()

' Set the row formatting
Dim rowFormat As 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));
[Visual Basic]

Dim doc As 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
Dim node As 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.
Dim para As New Paragraph(doc)
Dim table As 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#]

public void CalcuateDepthOfNestedTables()
{
    Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true))
    {
        // 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)
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells)
        {
            // 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;
}
[Visual Basic]

Public Sub CalcuateDepthOfNestedTables()
    Dim doc As New Document(MyDir & "Table.NestedTables.doc")
    Dim tableIndex As Integer = 0

    For Each table As Table In doc.GetChildNodes(NodeType.Table, True)
        ' First lets find if any cells in the table have tables themselves as children.
        Dim count As Integer = 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.
        Dim tableDepth As Integer = GetNestedDepthOfTable(table)

        If tableDepth > 0 Then
            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)
        End If

        tableIndex += 1
    Next table
End Sub

''' <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 Shared Function GetNestedDepthOfTable(ByVal table As Table) As Integer
    Dim depth As Integer = 0

    Dim type As NodeType = table.NodeType
    ' The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Dim parent As Node = table.GetAncestor(type)

    Do While parent IsNot Nothing
        ' 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 += 1
        parent = parent.GetAncestor(type)
    Loop

    Return depth
End Function

''' <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 Shared Function GetChildTableCount(ByVal table As Table) As Integer
    Dim tableCount As Integer = 0
    ' Iterate through all child rows in the table
    For Each row As Row In table.Rows
        ' Iterate through all child cells in the row
        For Each Cell As Cell In row.Cells
            ' Retrieve the collection of child tables of this cell
            Dim childTables As TableCollection = Cell.Tables

            ' If this cell has a table as a child then return true
            If childTables.Count > 0 Then
                tableCount += 1
            End If
        Next Cell
    Next row

    ' No cell contains a table
    Return tableCount
End Function

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(MyDir + "Table.PreferredWidth Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

' Insert a table with a width that takes up half the page width.
Dim table As 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(MyDir & "Table.PreferredWidth Out.doc")

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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As Table = builder.StartTable()
builder.InsertCell()

' Set the row formatting
Dim rowFormat As 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(MyDir + "Table.CombineTables Out.doc");
[Visual Basic]

' Load the document.
Dim doc As 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.
Dim firstTable As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
Dim secondTable As Table = CType(doc.GetChild(NodeType.Table, 1, True), Table)

' 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.
Do While secondTable.HasChildNodes
    firstTable.Rows.Add(secondTable.FirstRow)
Loop

' Remove the empty table container.
secondTable.Remove()

doc.Save(MyDir & "Table.CombineTables Out.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)
{
    // 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)
    {
        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)
        {
            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();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As 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).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table

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 import the data from a DataTable and insert it into a new table in the document.

[C#]

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

// We can position where we want the table to be inserted and also specify any extra formatting to be
// applied onto the table as well.
DocumentBuilder builder = new DocumentBuilder(doc);

// We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape;

// Retrieve the data from our data source which is stored as a DataTable.
DataTable dataTable = GetEmployees(databaseDir);

// Build a table in the document from the data contained in the DataTable.
Table table = ImportTableFromDataTable(builder, dataTable, true);

// We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1;
table.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.RowBands | TableStyleOptions.LastColumn;

// For our table we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren();

doc.Save(dataDir + "Table.FromDataTable Out.docx");
[Visual Basic]

' Create a new document.
Dim doc As New Document()

' We can position where we want the table to be inserted and also specify any extra formatting to be
' applied onto the table as well.
Dim builder As New DocumentBuilder(doc)

' We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape

' Retrieve the data from our data source which is stored as a DataTable.
Dim dataTable As DataTable = GetEmployees(databaseDir)

' Build a table in the document from the data contained in the DataTable.
Dim table As Table = ImportTableFromDataTable(builder, dataTable, True)

' We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1
table.StyleOptions = TableStyleOptions.FirstRow Or TableStyleOptions.RowBands Or TableStyleOptions.LastColumn

' For our table we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren()

doc.Save(dataDir & "Table.FromDataTable Out.docx")
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(MyDir + "DocumentBuilder.SetTableStyle Out.docx");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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 Or TableStyleOptions.RowBands Or 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(MyDir & "DocumentBuilder.SetTableStyle Out.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 import the data from a DataTable and insert it into a new table in the document.

[C#]

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

// We can position where we want the table to be inserted and also specify any extra formatting to be
// applied onto the table as well.
DocumentBuilder builder = new DocumentBuilder(doc);

// We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape;

// Retrieve the data from our data source which is stored as a DataTable.
DataTable dataTable = GetEmployees(databaseDir);

// Build a table in the document from the data contained in the DataTable.
Table table = ImportTableFromDataTable(builder, dataTable, true);

// We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1;
table.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.RowBands | TableStyleOptions.LastColumn;

// For our table we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren();

doc.Save(dataDir + "Table.FromDataTable Out.docx");
[Visual Basic]

' Create a new document.
Dim doc As New Document()

' We can position where we want the table to be inserted and also specify any extra formatting to be
' applied onto the table as well.
Dim builder As New DocumentBuilder(doc)

' We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape

' Retrieve the data from our data source which is stored as a DataTable.
Dim dataTable As DataTable = GetEmployees(databaseDir)

' Build a table in the document from the data contained in the DataTable.
Dim table As Table = ImportTableFromDataTable(builder, dataTable, True)

' We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1
table.StyleOptions = TableStyleOptions.FirstRow Or TableStyleOptions.RowBands Or TableStyleOptions.LastColumn

' For our table we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren()

doc.Save(dataDir & "Table.FromDataTable Out.docx")
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(MyDir + "DocumentBuilder.SetTableStyle Out.docx");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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 Or TableStyleOptions.RowBands Or 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(MyDir & "DocumentBuilder.SetTableStyle Out.docx")

See Also

Table Class | Aspose.Words.Tables Namespace


TextWrapping Property

Aspose.Words

Table.TextWrapping Property

Get or sets TextWrapping TextWrapping for table.

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

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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As Table = builder.StartTable()
builder.InsertCell()

' Set the row formatting
Dim rowFormat As 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


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) | Creates a duplicate of the node.
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) | Overloaded. Returns a collection of child nodes that match the specified type.
GetEnumerator (inherited from CompositeNode) | 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.
ToTxt (inherited from Node) | Obsolete. Exports the content of the node into a string in plain text 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#]

public void RemoveHiddenContentFromDocument()
{
    // 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(MyDir + "Font.Hidden Out.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 field)
    {
        if (isHidden(field))
            field.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 a DrawingML is encountered in the document.
    /// </summary>
    public override VisitorAction VisitDrawingML(DrawingML drawingML)
    {
        if (isHidden(drawingML))
            drawingML.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 algorthim,
        // 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 character)
    {
        if (isHidden(character))
            character.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)
        {
            // If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Inline currentNode = (Inline)node;
            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)
        {
            // Node is a shape or groupshape.
            ShapeBase shape = (ShapeBase)node;
            return shape.Font.Hidden;
        }
        else if (node is InlineStory)
        {
            // Node is a comment or footnote.
            InlineStory inlineStory = (InlineStory)node;
            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;
    }

}
[Visual Basic]

Public Sub RemoveHiddenContentFromDocument()
    ' Open the document we want to remove hidden content from.
    Dim doc As New Document(MyDir & "Font.Hidden.doc")

    ' Create an object that inherits from the DocumentVisitor class.
    Dim hiddenContentRemover As 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.
    Dim para As Paragraph = CType(doc.GetChild(NodeType.Paragraph, 4, True), Paragraph)
    para.Accept(hiddenContentRemover)

    ' Or over a different type of node like below.
    Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
    table.Accept(hiddenContentRemover)

    doc.Save(MyDir & "Font.Hidden Out.doc")

End Sub

''' <summary>
''' This class when executed will remove all hidden content from the Document. Implemented as a Visitor.
''' </summary>
Private Class RemoveHiddenContentVisitor
    Inherits DocumentVisitor
    ''' <summary>
    ''' Called when a FieldStart node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldStart(ByVal fieldStart As FieldStart) As VisitorAction
        ' If this node is hidden, then remove it.
        If isHidden(fieldStart) Then
            fieldStart.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldEnd node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldEnd(ByVal fieldEnd As FieldEnd) As VisitorAction
        If isHidden(fieldEnd) Then
            fieldEnd.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FieldSeparator node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFieldSeparator(ByVal fieldSeparator As FieldSeparator) As VisitorAction
        If isHidden(fieldSeparator) Then
            fieldSeparator.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Run node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitRun(ByVal run As Run) As VisitorAction
        If isHidden(run) Then
            run.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Paragraph node is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitParagraphStart(ByVal paragraph As Paragraph) As VisitorAction
        If isHidden(paragraph) Then
            paragraph.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a FormField is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFormField(ByVal field As FormField) As VisitorAction
        If isHidden(field) Then
            field.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a GroupShape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitGroupShapeStart(ByVal groupShape As GroupShape) As VisitorAction
        If isHidden(groupShape) Then
            groupShape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Shape is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitShapeStart(ByVal shape As Shape) As VisitorAction
        If isHidden(shape) Then
            shape.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Comment is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitCommentStart(ByVal comment As Comment) As VisitorAction
        If isHidden(comment) Then
            comment.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a Footnote is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitFootnoteStart(ByVal footnote As Footnote) As VisitorAction
        If isHidden(footnote) Then
            footnote.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a DrawingML is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitDrawingML(ByVal drawingML As DrawingML) As VisitorAction
        If isHidden(drawingML) Then
            drawingML.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Table node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitTableEnd(ByVal table As Table) As VisitorAction
        ' 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 algorthim,
        ' as technically they are not completely empty (for example a properly formed Cell will have at least
        ' an empty paragraph in it)
        If (Not table.HasChildNodes) Then
            table.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Cell node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitCellEnd(ByVal cell As Cell) As VisitorAction
        If (Not cell.HasChildNodes) AndAlso cell.ParentNode IsNot Nothing Then
            cell.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when visiting of a Row node is ended in the document.
    ''' </summary>
    Public Overrides Function VisitRowEnd(ByVal row As Row) As VisitorAction
        If (Not row.HasChildNodes) AndAlso row.ParentNode IsNot Nothing Then
            row.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Called when a SpecialCharacter is encountered in the document.
    ''' </summary>
    Public Overrides Function VisitSpecialChar(ByVal character As SpecialChar) As VisitorAction
        If isHidden(character) Then
            character.Remove()
        End If

        Return VisitorAction.Continue
    End Function

    ''' <summary>
    ''' Returns true if the node passed is set as hidden, returns false if it is visible.
    ''' </summary>
    Private Function isHidden(ByVal node As Node) As Boolean
        If TypeOf node Is Inline Then
            ' If the node is Inline then cast it to retrieve the Font property which contains the hidden property
            Dim currentNode As Inline = CType(node, Inline)
            Return currentNode.Font.Hidden
        ElseIf node.NodeType = NodeType.Paragraph Then
            ' If the node is a paragraph cast it to retrieve the ParagraphBreakFont which contains the hidden property
            Dim para As Paragraph = CType(node, Paragraph)
            Return para.ParagraphBreakFont.Hidden
        ElseIf TypeOf node Is ShapeBase Then
            ' Node is a shape or groupshape.
            Dim shape As ShapeBase = CType(node, ShapeBase)
            Return shape.Font.Hidden
        ElseIf TypeOf node Is InlineStory Then
            ' Node is a comment or footnote.
            Dim inlineStory As InlineStory = CType(node, InlineStory)
            Return inlineStory.Font.Hidden
        End If

        ' 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
    End Function

End Class

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

Disables autofitting and enables fixed widths for the specified table.

[C#]

// Open the document
Document doc = new Document(dataDir + "TestFile.doc");

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// Disable autofitting on this table.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Save the document to disk.
doc.Save(dataDir + "TestFile.FixedWidth Out.doc");
[Visual Basic]

' Open the document
Dim doc As New Document(dataDir & "TestFile.doc")

Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Disable autofitting on this table.
table.AutoFit(AutoFitBehavior.FixedColumnWidths)

' Save the document to disk.
doc.Save(dataDir & "TestFile.FixedWidth Out.doc")
Autofits a table to fit the page width.
[C#]

// Open the document
Document doc = new Document(dataDir + "TestFile.doc");

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// Autofit the first table to the page width.
table.AutoFit(AutoFitBehavior.AutoFitToWindow);

// Save the document to disk.
doc.Save(dataDir + "TestFile.AutoFitToWindow Out.doc");
[Visual Basic]

' Open the document
Dim doc As New Document(dataDir & "TestFile.doc")

Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Autofit the first table to the page width.
table.AutoFit(AutoFitBehavior.AutoFitToWindow)

' Save the document to disk.
doc.Save(dataDir & "TestFile.AutoFitToWindow Out.doc")
Autofits a table in the document to its contents.
[C#]

// Open the document
Document doc = new Document(dataDir + "TestFile.doc");

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// Auto fit the table to the cell contents
table.AutoFit(AutoFitBehavior.AutoFitToContents);

// Save the document to disk.
doc.Save(dataDir + "TestFile.AutoFitToContents Out.doc");
[Visual Basic]

' Open the document
Dim doc As New Document(dataDir & "TestFile.doc")

Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Auto fit the table to the cell contents
table.AutoFit(AutoFitBehavior.AutoFitToContents)

' Save the document to disk.
doc.Save(dataDir & "TestFile.AutoFitToContents Out.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();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir + "DocumentBuilder.SetTableStyle Out.docx");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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 Or TableStyleOptions.RowBands Or 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(MyDir & "DocumentBuilder.SetTableStyle Out.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(MyDir + "Table.ClearBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")

' Remove all borders from the first table in the document.
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Clear the borders all cells in the table.
table.ClearBorders()

doc.Save(MyDir & "Table.ClearBorders Out.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(MyDir + "Table.SetOutlineBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.EmptyTable.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' 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(MyDir & "Table.SetOutlineBorders Out.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.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();
[Visual Basic]

Dim doc As New Document()

' Create a new table and add it to the document.
Dim table As 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(MyDir + "Table.SetOutlineBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.EmptyTable.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' 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(MyDir & "Table.SetOutlineBorders Out.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(MyDir + "Table.SetAllBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.EmptyTable.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' 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(MyDir & "Table.SetAllBorders Out.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(MyDir + "Table.SetBordersAndShading Out.doc");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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(MyDir & "Table.SetBordersAndShading Out.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(MyDir + "Table.SetOutlineBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.EmptyTable.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' 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(MyDir & "Table.SetOutlineBorders Out.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(MyDir + "Table.SetOutlineBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.EmptyTable.doc")
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' 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(MyDir & "Table.SetOutlineBorders Out.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)
{
    // Quick typed access to the first row of the table.
    if (table.FirstRow != null)
        table.FirstRow.Remove();

    // Quick typed access to the last row of the table.
    if (table.LastRow != null)
        table.LastRow.Remove();
}
[Visual Basic]

' Quick typed access to the first child Section node of the Document.
Dim section As Section = doc.FirstSection

' Quick typed access to the Body child node of the Section.
Dim body As Body = section.Body

' Quick typed access to all Table child nodes contained in the Body.
Dim tables As TableCollection = body.Tables

For Each table As Table In tables
    ' Quick typed access to the first row of the table.
    If table.FirstRow IsNot Nothing Then
        table.FirstRow.Remove()
    End If

    ' Quick typed access to the last row of the table.
    If table.LastRow IsNot Nothing Then
        table.LastRow.Remove()
    End If
Next table
Shows how to find out if a table contains another table or if the table itself is nested inside another table.
[C#]

public void CalcuateDepthOfNestedTables()
{
    Document doc = new Document(MyDir + "Table.NestedTables.doc");
    int tableIndex = 0;

    foreach (Table table in doc.GetChildNodes(NodeType.Table, true))
    {
        // 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)
    {
        // Iterate through all child cells in the row
        foreach (Cell Cell in row.Cells)
        {
            // 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;
}
[Visual Basic]

Public Sub CalcuateDepthOfNestedTables()
    Dim doc As New Document(MyDir & "Table.NestedTables.doc")
    Dim tableIndex As Integer = 0

    For Each table As Table In doc.GetChildNodes(NodeType.Table, True)
        ' First lets find if any cells in the table have tables themselves as children.
        Dim count As Integer = 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.
        Dim tableDepth As Integer = GetNestedDepthOfTable(table)

        If tableDepth > 0 Then
            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)
        End If

        tableIndex += 1
    Next table
End Sub

''' <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 Shared Function GetNestedDepthOfTable(ByVal table As Table) As Integer
    Dim depth As Integer = 0

    Dim type As NodeType = table.NodeType
    ' The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
    Dim parent As Node = table.GetAncestor(type)

    Do While parent IsNot Nothing
        ' 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 += 1
        parent = parent.GetAncestor(type)
    Loop

    Return depth
End Function

''' <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 Shared Function GetChildTableCount(ByVal table As Table) As Integer
    Dim tableCount As Integer = 0
    ' Iterate through all child rows in the table
    For Each row As Row In table.Rows
        ' Iterate through all child cells in the row
        For Each Cell As Cell In row.Cells
            ' Retrieve the collection of child tables of this cell
            Dim childTables As TableCollection = Cell.Tables

            ' If this cell has a table as a child then return true
            If childTables.Count > 0 Then
                tableCount += 1
            End If
        Next Cell
    Next row

    ' No cell contains a table
    Return tableCount
End Function

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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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 NodeCollection) | Provides a simple "foreach" style iteration over the collection of nodes.
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 import the data from a DataTable and insert it into a new table in the document.

[C#]

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

// We can position where we want the table to be inserted and also specify any extra formatting to be
// applied onto the table as well.
DocumentBuilder builder = new DocumentBuilder(doc);

// We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape;

// Retrieve the data from our data source which is stored as a DataTable.
DataTable dataTable = GetEmployees(databaseDir);

// Build a table in the document from the data contained in the DataTable.
Table table = ImportTableFromDataTable(builder, dataTable, true);

// We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1;
table.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.RowBands | TableStyleOptions.LastColumn;

// For our table we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren();

doc.Save(dataDir + "Table.FromDataTable Out.docx");
[Visual Basic]

' Create a new document.
Dim doc As New Document()

' We can position where we want the table to be inserted and also specify any extra formatting to be
' applied onto the table as well.
Dim builder As New DocumentBuilder(doc)

' We want to rotate the page landscape as we expect a wide table.
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape

' Retrieve the data from our data source which is stored as a DataTable.
Dim dataTable As DataTable = GetEmployees(databaseDir)

' Build a table in the document from the data contained in the DataTable.
Dim table As Table = ImportTableFromDataTable(builder, dataTable, True)

' We can apply a table style as a very quick way to apply formatting to the entire table.
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1
table.StyleOptions = TableStyleOptions.FirstRow Or TableStyleOptions.RowBands Or TableStyleOptions.LastColumn

' For our table we want to remove the heading for the image column.
table.FirstRow.LastCell.RemoveAllChildren()

doc.Save(dataDir & "Table.FromDataTable Out.docx")
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(MyDir + "DocumentBuilder.SetTableStyle Out.docx");
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As 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 Or TableStyleOptions.RowBands Or 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(MyDir & "DocumentBuilder.SetTableStyle Out.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.BuildingBlocksHierarchy

Aspose.Words

Aspose.Words.BuildingBlocks Hierarchy

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.BuildingBlocks.BuildingBlock
Aspose.Words.DocumentBase
Aspose.Words.BuildingBlocks.GlossaryDocument
Aspose.Words.NodeCollection ---- 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
CustomXmlMarkup
SmartTag
StructuredDocumentTag
OfficeMath
Paragraph
Section
Story
Cell
Row
Table

See Also

CompositeNode Class | CompositeNode Members | Aspose.Words Namespace


Aspose.Words.DrawingHierarchy

Aspose.Words

Aspose.Words.Drawing Hierarchy

System.Object
Aspose.Words.Drawing.DrawingMLImageData ---- Aspose.Words.Drawing.IImageData
Aspose.Words.Drawing.Fill
Aspose.Words.Drawing.IImageData
Aspose.Words.Drawing.ImageData ---- Aspose.Words.Drawing.IImageData
Aspose.Words.Drawing.ImageSize
Aspose.Words.Drawing.OleFormat
Aspose.Words.Drawing.Stroke
Aspose.Words.Drawing.TextBox
Aspose.Words.Drawing.TextPath
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.Drawing.ShapeBase
Aspose.Words.Drawing.GroupShape
Aspose.Words.Drawing.Shape
Aspose.Words.Inline
Aspose.Words.Drawing.DrawingML
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.ShapeType
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


Aspose.Words.FieldsHierarchy

Aspose.Words

Aspose.Words.Fields Hierarchy

System.Object
Aspose.Words.Fields.DropDownItemCollection ---- System.Collections.IEnumerable
Aspose.Words.Fields.Field
Aspose.Words.Fields.FieldCollection ---- System.Collections.IEnumerable
Aspose.Words.Fields.FieldOptions
Aspose.Words.Fields.FormFieldCollection ---- System.Collections.IEnumerable
Aspose.Words.Fields.IFieldUserPromptRespondent
Aspose.Words.Fields.MergeFieldImageDimension
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.FieldType
Aspose.Words.Fields.FieldUpdateCultureSource
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.FontInfo
Aspose.Words.Fonts.FontInfoCollection ---- 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.SystemFontSource
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

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.IEnumerable
Aspose.Words.Lists.ListLabel
Aspose.Words.Lists.ListLevel
Aspose.Words.Lists.ListLevelCollection ---- 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.MarkupHierarchy

Aspose.Words

Aspose.Words.Markup Hierarchy

System.Object
Aspose.Words.Markup.CustomPart
Aspose.Words.Markup.CustomPartCollection ---- System.Collections.IEnumerable
Aspose.Words.Markup.CustomXmlPart
Aspose.Words.Markup.CustomXmlPartCollection ---- System.Collections.IEnumerable
Aspose.Words.Markup.CustomXmlProperty
Aspose.Words.Markup.CustomXmlPropertyCollection ---- System.Collections.IEnumerable
Aspose.Words.Markup.CustomXmlSchemaCollection ---- System.Collections.IEnumerable
Aspose.Words.Markup.SdtListItem
Aspose.Words.Markup.SdtListItemCollection ---- System.Collections.IEnumerable
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.Markup.CustomXmlMarkup
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.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.Math.OfficeMath

See Also

Aspose.Words.Math Namespace


NodeCollection Hierarchy

System.Object
NodeCollection
BuildingBlockCollection
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.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.PageInfo
Aspose.Words.Rendering.PrinterSettingsContainer
Aspose.Words.Rendering.ShapeRenderer
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.ReportingHierarchy

Aspose.Words

Aspose.Words.Reporting Hierarchy

System.Object
Aspose.Words.Reporting.FieldMergingArgsBase
Aspose.Words.Reporting.FieldMergingArgs
Aspose.Words.Reporting.ImageFieldMergingArgs
Aspose.Words.Reporting.IFieldMergingCallback
Aspose.Words.Reporting.IMailMergeDataSource
Aspose.Words.Reporting.IMailMergeDataSourceRoot
Aspose.Words.Reporting.MailMerge
Aspose.Words.Reporting.MappedDataFieldCollection ---- System.Collections.IEnumerable
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
Aspose.Words.Reporting.MailMergeCleanupOptions
Aspose.Words.Reporting.MailMergeRtlCleanupMode

See Also

Aspose.Words.Reporting Namespace


SaveOptions Hierarchy

System.Object
SaveOptions
DocSaveOptions
HtmlFixedSaveOptions
HtmlSaveOptions
ImageSaveOptions
OdtSaveOptions
OoxmlSaveOptions
PdfSaveOptions
PsSaveOptions
RtfSaveOptions
SvgSaveOptions
SwfSaveOptions
TxtSaveOptions
WordML2003SaveOptions
XamlFixedSaveOptions
XamlFlowSaveOptions
XpsSaveOptions

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.IEnumerable
Aspose.Words.Saving.CssSavingArgs
Aspose.Words.Saving.DocumentPartSavingArgs
Aspose.Words.Saving.DownsampleOptions
Aspose.Words.Saving.FontSavingArgs
Aspose.Words.Saving.ICssSavingCallback
Aspose.Words.Saving.IDocumentPartSavingCallback
Aspose.Words.Saving.IFontSavingCallback
Aspose.Words.Saving.IImageSavingCallback
Aspose.Words.Saving.ImageSavingArgs
Aspose.Words.Saving.IResourceSavingCallback
Aspose.Words.Saving.MetafileRenderingOptions
Aspose.Words.Saving.OutlineOptions
Aspose.Words.Saving.PdfDigitalSignatureDetails
Aspose.Words.Saving.PdfEncryptionDetails
Aspose.Words.Saving.ResourceSavingArgs
Aspose.Words.Saving.SaveOptions
Aspose.Words.Saving.DocSaveOptions
Aspose.Words.Saving.HtmlFixedSaveOptions
Aspose.Words.Saving.HtmlSaveOptions
Aspose.Words.Saving.ImageSaveOptions
Aspose.Words.Saving.OdtSaveOptions
Aspose.Words.Saving.OoxmlSaveOptions
Aspose.Words.Saving.PdfSaveOptions
Aspose.Words.Saving.PsSaveOptions
Aspose.Words.Saving.RtfSaveOptions
Aspose.Words.Saving.SvgSaveOptions
Aspose.Words.Saving.SwfSaveOptions
Aspose.Words.Saving.TxtSaveOptions
Aspose.Words.Saving.WordML2003SaveOptions
Aspose.Words.Saving.XamlFixedSaveOptions
Aspose.Words.Saving.XamlFlowSaveOptions
Aspose.Words.Saving.XpsSaveOptions
Aspose.Words.Saving.SaveOutputParameters
Aspose.Words.Saving.SwfToolTips
System.ValueType
System.Enum ---- System.IComparable, System.IConvertible, System.IFormattable
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.HtmlElementSizeOutputMode
Aspose.Words.Saving.ImageBinarizationMethod
Aspose.Words.Saving.ImageColorMode
Aspose.Words.Saving.ImagePixelFormat
Aspose.Words.Saving.MetafileRenderingMode
Aspose.Words.Saving.NumeralFormat
Aspose.Words.Saving.OoxmlCompliance
Aspose.Words.Saving.PdfCompliance
Aspose.Words.Saving.PdfDigitalSignatureHashAlgorithm
Aspose.Words.Saving.PdfEncryptionAlgorithm
Aspose.Words.Saving.PdfFontEmbeddingMode
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.SwfLeftPaneControlFlags
Aspose.Words.Saving.SwfTopPaneControlFlags
Aspose.Words.Saving.SwfViewerControlIdentifier
Aspose.Words.Saving.TiffCompression

See Also

Aspose.Words.Saving Namespace


Aspose.Words.SettingsHierarchy

Aspose.Words

Aspose.Words.Settings Hierarchy

System.Object
Aspose.Words.Settings.CompatibilityOptions
Aspose.Words.Settings.MailMergeSettings
Aspose.Words.Settings.Odso
Aspose.Words.Settings.OdsoFieldMapData
Aspose.Words.Settings.OdsoFieldMapDataCollection ---- System.Collections.IEnumerable
Aspose.Words.Settings.OdsoRecipientData
Aspose.Words.Settings.OdsoRecipientDataCollection ---- 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.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.TablesHierarchy

Aspose.Words

Aspose.Words.Tables Hierarchy

System.Object
Aspose.Words.Node
Aspose.Words.CompositeNode ---- System.Collections.IEnumerable, System.Xml.XPath.IXPathNavigable
Aspose.Words.Tables.Cell
Aspose.Words.Tables.Row
Aspose.Words.Tables.Table
Aspose.Words.NodeCollection ---- 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.RowAlignment
Aspose.Words.Tables.TableAlignment
Aspose.Words.Tables.TableStyleOptions
Aspose.Words.Tables.TextWrapping

See Also

Aspose.Words.Tables Namespace


Aspose.WordsHierarchy

Aspose.Words

Aspose.Words Hierarchy

System.Object
Aspose.Words.Bookmark
Aspose.Words.BookmarkCollection ---- System.Collections.IEnumerable
Aspose.Words.Border
Aspose.Words.BorderCollection ---- System.Collections.IEnumerable
Aspose.Words.BuildVersionInfo
Aspose.Words.ComHelper
Aspose.Words.ControlChar
Aspose.Words.ConvertUtil
Aspose.Words.DigitalSignature
Aspose.Words.DigitalSignatureCollection ---- System.Collections.IEnumerable
Aspose.Words.DigitalSignatureUtil
Aspose.Words.DocumentBuilder
Aspose.Words.DocumentVisitor
Aspose.Words.EditableRange
Aspose.Words.FileFormatInfo
Aspose.Words.FileFormatUtil
Aspose.Words.Font
Aspose.Words.FootnoteOptions
Aspose.Words.Hyphenation
Aspose.Words.IHyphenationCallback
Aspose.Words.INodeChangingCallback
Aspose.Words.InterruptionToken
Aspose.Words.IReplacingCallback
Aspose.Words.IWarningCallback
Aspose.Words.License
Aspose.Words.ListFormat
Aspose.Words.LoadOptions
Aspose.Words.Node
Aspose.Words.BookmarkEnd
Aspose.Words.BookmarkStart
Aspose.Words.CommentRangeEnd
Aspose.Words.CommentRangeStart
Aspose.Words.CompositeNode ---- 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.IEnumerable
Aspose.Words.HeaderFooterCollection
Aspose.Words.ParagraphCollection
Aspose.Words.RunCollection
Aspose.Words.SectionCollection
Aspose.Words.NodeImporter
Aspose.Words.NodeList ---- System.Collections.IEnumerable
Aspose.Words.PageSetup
Aspose.Words.ParagraphFormat
Aspose.Words.Range
Aspose.Words.ReplacingArgs
Aspose.Words.Revision
Aspose.Words.RevisionCollection ---- System.Collections.IEnumerable
Aspose.Words.Shading
Aspose.Words.Style
Aspose.Words.TableStyle
Aspose.Words.StyleCollection ---- System.Collections.IEnumerable
Aspose.Words.TabStop
Aspose.Words.TabStopCollection
Aspose.Words.TextColumn
Aspose.Words.TextColumnCollection
Aspose.Words.VariableCollection ---- System.Collections.IEnumerable
Aspose.Words.WarningInfo
Aspose.Words.WarningInfoCollection ---- Aspose.Words.IWarningCallback, 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.ContentDisposition
Aspose.Words.DigitalSignatureType
Aspose.Words.DropCapPosition
Aspose.Words.EditorType
Aspose.Words.FootnoteLocation
Aspose.Words.FootnoteNumberingRule
Aspose.Words.FootnoteType
Aspose.Words.HeaderFooterType
Aspose.Words.HeightRule
Aspose.Words.ImportFormatMode
Aspose.Words.LineNumberRestartMode
Aspose.Words.LineSpacingRule
Aspose.Words.LineStyle
Aspose.Words.LoadFormat
Aspose.Words.MsWordVersion
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.ReplaceAction
Aspose.Words.RevisionType
Aspose.Words.SaveFormat
Aspose.Words.SectionStart
Aspose.Words.StoryType
Aspose.Words.StyleIdentifier
Aspose.Words.StyleType
Aspose.Words.TabAlignment
Aspose.Words.TabLeader
Aspose.Words.TextEffect
Aspose.Words.TextOrientation
Aspose.Words.TextureIndex
Aspose.Words.Underline
Aspose.Words.VisitorAction
Aspose.Words.WarningSource
Aspose.Words.WarningType

See Also

Aspose.Words Namespace