Class WordDocument
Represents a Word document and can be used to create a new Word document from the scratch.
Inheritance
Inherited Members
Namespace: Syncfusion.DocIO.DLS
Assembly: Syncfusion.DocIO.UWP.dll
Syntax
public class WordDocument : WidgetContainer, IXDLSSerializable, IWordDocument, ICompositeEntity, IEntity, IDisposable, IWidgetContainer, IWidget
Examples
//Create an new instance of WordDocument class
WordDocument document = new WordDocument();
//Add a new section into the Word document
IWSection section = document.AddSection();
//Specify the page margins
section.PageSetup.Margins.All = 50f;
//Add a new simple paragraph into the section
IWParagraph paragraph = section.AddParagraph();
//Add a text range into the paragraph
paragraph.AppendText("Hello World!");
//Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx);
//Release the resources occupied by WordDocument instance
document.Close();
'Create an instance of WordDocument class
Dim document As New WordDocument()
'Add a new section into the Word document
Dim section As IWSection = document.AddSection()
'Specify the page margins
section.PageSetup.Margins.All = 50F
'Add a new simple paragraph into the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Add a text range into the paragraph
paragraph.AppendText("Hello World!")
'Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx)
'Release the resources occupied by WordDocument instance
document.Close()
Constructors
WordDocument()
Initializes a new instance of the WordDocument class.
Declaration
public WordDocument()
Examples
//Create an instance of WordDocument class
WordDocument document = new WordDocument();
//Add a new section into the Word document
IWSection section = document.AddSection();
//Specify the page margins
section.PageSetup.Margins.All = 50f;
//Add a new simple paragraph into the section
IWParagraph paragraph = section.AddParagraph();
//Add a text range into the paragraph
paragraph.AppendText("Hello World!");
//Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx);
//Release the resources occupied by WordDocument instance
document.Close();
'Create an instance of WordDocument class
Dim document As New WordDocument()
'Add a new section into the Word document
Dim section As IWSection = document.AddSection()
'Specify the page margins
section.PageSetup.Margins.All = 50F
'Add a new simple paragraph into the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Add a text range into the paragraph
paragraph.AppendText("Hello World!")
'Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx)
'Release the resources occupied by WordDocument instance
document.Close()
See Also
WordDocument(WordDocument)
Initializes a new instance of the WordDocument class from the existing WordDocument
instance.
Declaration
protected WordDocument(WordDocument doc)
Parameters
Type | Name | Description |
---|---|---|
WordDocument | doc | The WordDocument instance used to create this WordDocument. |
WordDocument(Stream)
Initializes a new instance of the WordDocument class from the existing data stream.
Declaration
public WordDocument(Stream stream)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream that contains the data for this WordDocument. |
Examples
Stream fileStream = new FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read);
//Load an existing Stream into WordDocument instance
WordDocument document = new WordDocument(fileStream);
//Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx);
//Release the resources occupied by WordDocument instance
document.Close();
Dim fileStream As Stream = New FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read)
'Load an existing Stream into WordDocument instance
Dim document As New WordDocument(fileStream)
'Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx)
'Release the resources occupied by WordDocument instance
document.Close()
WordDocument(Stream, FormatType)
Initializes a new instance of the WordDocument class from the existing data stream of the specified file format type.
Declaration
public WordDocument(Stream stream, FormatType type)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream that contains the data for this WordDocument. |
FormatType | type | The file format type of this WordDocument. |
Examples
Stream fileStream = new FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read);
//Load an existing Stream into WordDocument instance
WordDocument document = new WordDocument(fileStream, FormatType.Docx);
//Add a new simple paragraph into the last section of the document
IWParagraph paragraph = document.LastSection.AddParagraph();
//Add a text range into the paragraph
paragraph.AppendText("Hello World!");
//Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx);
//Release the resources occupied by WordDocument instance
document.Close();
Dim fileStream As Stream = New FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read)
'Load an existing Stream into WordDocument instance
Dim document As New WordDocument(fileStream, FormatType.Docx)
'Add a new simple paragraph into the last section of the document
Dim paragraph As IWParagraph = document.LastSection.AddParagraph()
'Add a text range into the paragraph
paragraph.AppendText("Hello World!")
'Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx)
'Release the resources occupied by WordDocument instance
document.Close()
WordDocument(Stream, FormatType, String)
Initializes a new instance of the WordDocument class from the existing data stream of the specified file format type, which is protected with password.
Declaration
public WordDocument(Stream stream, FormatType type, string password)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream that contains the data for this WordDocument. |
FormatType | type | The file format type of this WordDocument. |
System.String | password | The password used to decrypt the protected file. |
Remarks
This API is supported from .NET Framework 2.0 and .NET Standard 2.0 onwards.
Examples
Stream fileStream = new FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read);
//Load an existing Stream into WordDocument instance
WordDocument document = new WordDocument(fileStream, FormatType.Docx, "password");
//Add a new simple paragraph into the last section of the document
IWParagraph paragraph = document.LastSection.AddParagraph();
//Add a text range into the paragraph
paragraph.AppendText("Hello World!");
//Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx);
//Release the resources occupied by WordDocument instance
document.Close();
Dim fileStream As Stream = New FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read)
'Load an existing Stream into WordDocument instance
Dim document As New WordDocument(fileStream, FormatType.Docx, "password")
'Add a new simple paragraph into the last section of the document
Dim paragraph As IWParagraph = document.LastSection.AddParagraph()
'Add a text range into the paragraph
paragraph.AppendText("Hello World!")
'Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx)
'Release the resources occupied by WordDocument instance
document.Close()
WordDocument(Stream, String)
Initializes a new instance of the WordDocument class from the existing data stream, which is protected with password.
Declaration
public WordDocument(Stream stream, string password)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream that contains the data for this WordDocument. |
System.String | password | The password used to decrypt the protected file. |
Remarks
This API is supported from .NET Framework 2.0 and .NET Standard 2.0 onwards.
Examples
Stream fileStream = new FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read);
//Load an existing Stream into WordDocument instance
WordDocument document = new WordDocument(fileStream, "password");
//Add a new simple paragraph into the last section of the document
IWParagraph paragraph = document.LastSection.AddParagraph();
//Add a text range into the paragraph
paragraph.AppendText("Hello World!");
//Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx);
//Release the resources occupied by WordDocument instance
document.Close();
Dim fileStream As Stream = New FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read)
'Load an existing Stream into WordDocument instance
Dim document As New WordDocument(fileStream, "password")
'Add a new simple paragraph into the last section of the document
Dim paragraph As IWParagraph = document.LastSection.AddParagraph()
'Add a text range into the paragraph
paragraph.AppendText("Hello World!")
'Save the document in the given name and format
document.Save("Document.docx", FormatType.Docx)
'Release the resources occupied by WordDocument instance
document.Close()
Fields
m_sections
Collection of document sections
Declaration
protected WSectionCollection m_sections
Field Value
Type |
---|
WSectionCollection |
m_styles
Collection of document styles
Declaration
protected IStyleCollection m_styles
Field Value
Type |
---|
IStyleCollection |
Properties
ActualFormatType
Gets the actual format type of the document which was loaded. While creating new document, it returns FormatType.Doc value. Read-only.
Declaration
public FormatType ActualFormatType { get; }
Property Value
Type | Description |
---|---|
FormatType | The file format type of this WordDocument |
AttachedTemplate
Gets a Template object that represents the attached template of the document. Read-only.
Declaration
public Template AttachedTemplate { get; }
Property Value
Type | Description |
---|---|
Template | Attached template of the document |
See Also
Background
Gets the Background object that represents the background effects of the document. Read-only.
Declaration
public Background Background { get; }
Property Value
Type | Description |
---|---|
Background | The background effects of the document |
See Also
BackgroundImage
Gets or sets the background image of a document.
Declaration
public byte[] BackgroundImage { get; set; }
Property Value
Type |
---|
System.Byte[] |
See Also
Bookmarks
Gets a BookmarkCollection collection that represents all the bookmarks in the document. Read-only.
Declaration
public BookmarkCollection Bookmarks { get; }
Property Value
Type |
---|
BookmarkCollection |
See Also
BuiltinDocumentProperties
Gets a BuiltinDocumentProperties collection that represents all the built-in document properties for the specified document. Read-only.
Declaration
public BuiltinDocumentProperties BuiltinDocumentProperties { get; }
Property Value
Type |
---|
BuiltinDocumentProperties |
See Also
ChildEntities
Gets the EntityCollection collection that represents the child entities of this WordDocument. Read-only.
Declaration
public EntityCollection ChildEntities { get; }
Property Value
Type | Description |
---|---|
EntityCollection | The child entities. |
Comments
Gets a CommentsCollection collection that represents all the comments in the document. Read-only.
Declaration
public CommentsCollection Comments { get; }
Property Value
Type |
---|
CommentsCollection |
See Also
ContentTypeProperties
Gets a MetaProperties the metadata stored in a document, such as author name, subject, and company. Read-only.
Declaration
public MetaProperties ContentTypeProperties { get; }
Property Value
Type | Description |
---|---|
MetaProperties | A MetaProperties collection represents all the MetaProperty in this WordDocument |
See Also
CustomDocumentProperties
Gets a CustomDocumentProperties collection that represents all the custom document properties for the specified document. Read-only.
Declaration
public CustomDocumentProperties CustomDocumentProperties { get; }
Property Value
Type |
---|
CustomDocumentProperties |
DefaultTabWidth
Gets or sets the default tab stop position value measured in points.
Declaration
public float DefaultTabWidth { get; set; }
Property Value
Type | Description |
---|---|
System.Single | The width of the default tab. |
See Also
EnablePartialTrustCode
Gets or sets a value indicating whether to run the partial trust code.
Declaration
public static bool EnablePartialTrustCode { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean | True if to run partial trust code; otherwise, false. |
EndnoteNumberFormat
Gets or sets the numbering format for the endnotes in the document.
Declaration
public FootEndNoteNumberFormat EndnoteNumberFormat { get; set; }
Property Value
Type | Description |
---|---|
FootEndNoteNumberFormat | The FootEndNoteNumberFormat for the endnotes in the Word document |
Examples
The following code example demonstrates how to specify the endnote number format in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the endnote format
document.EndnoteNumberFormat = FootEndNoteNumberFormat.Arabic;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the endnote format
document.EndnoteNumberFormat = FootEndNoteNumberFormat.Arabic
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
EndnotePosition
Gets or sets endnotes position in the document.
Declaration
public EndnotePosition EndnotePosition { get; set; }
Property Value
Type | Description |
---|---|
EndnotePosition | The EndnotePosition for the endnotes in the document |
Examples
The following code example demonstrates how to specify the endnote position in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the endnote position at end of each section
document.EndnotePosition = EndnotePosition.DisplayEndOfSection;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the endnote position at end of each section
document.EndnotePosition = EndnotePosition.DisplayEndOfSection
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Endnotes
Gets or sets the endnote separators of the document.
Declaration
public Endnote Endnotes { get; set; }
Property Value
Type | Description |
---|---|
Endnote | The Endnote instance used to specify the endnote separator of this WordDocument. |
See Also
EntityType
Gets the type of the entity.
Declaration
public override EntityType EntityType { get; }
Property Value
Type | Description |
---|---|
EntityType | The EntityType of the current item. |
Overrides
FontSubstitutionTable
Gets or sets a dictionary collections which represents the font substitution table. The key should be the font name and the value should be the alternate font name.
Declaration
public Dictionary<string, string> FontSubstitutionTable { get; set; }
Property Value
Type | Description |
---|---|
System.Collections.Generic.Dictionary<System.String, System.String> | The font substitution table contains an alternative font information for missing fonts in the document. |
Examples
The following code example demonstrates how to specify the alternative font information for missing fonts in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Apply the Arial font instead of the Arabic font, if the system does not contains Arabic font
document.FontSubstitutionTable.Add("Arabic", "Arial");
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Apply the Arial font instead of the Arabic font, if the system does not contains Arabic font
document.FontSubstitutionTable.Add("Arabic", "Arial");
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
FootnoteNumberFormat
Gets or sets the numbering format for the footnotes in the document.
Declaration
public FootEndNoteNumberFormat FootnoteNumberFormat { get; set; }
Property Value
Type | Description |
---|---|
FootEndNoteNumberFormat | The FootEndNoteNumberFormat for the footnotes in the Word document |
Examples
The following code example demonstrates how to specify the footnote number format in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the footnote number format
document.FootnoteNumberFormat = FootEndNoteNumberFormat.UpperCaseRoman;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the footnote number format
document.FootnoteNumberFormat = FootEndNoteNumberFormat.UpperCaseRoman
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
FootnotePosition
Gets or sets footnotes position in the document.
Declaration
public FootnotePosition FootnotePosition { get; set; }
Property Value
Type | Description |
---|---|
FootnotePosition | The FootnotePosition for the footnote in the document |
Examples
The following code example demonstrates how to specify the footnote position in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the footnote position at immediately beneath text
document.FootnotePosition = FootnotePosition.PrintImmediatelyBeneathText;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the footnote position at immediately beneath text
document.FootnotePosition = FootnotePosition.PrintImmediatelyBeneathText
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Footnotes
Gets or sets the footnote separators of the document.
Declaration
public Footnote Footnotes { get; set; }
Property Value
Type | Description |
---|---|
Footnote | The Footnote instance used to specify the footnote separator of this WordDocument. |
See Also
HasChanges
Gets a value indicating whether the document has tracked changes. Read-only.
Declaration
public bool HasChanges { get; }
Property Value
Type | Description |
---|---|
System.Boolean | True if the document has tracked changes; otherwise, false. |
HasMacros
Gets a value indicating whether the document has macros. Read-only.
Declaration
public bool HasMacros { get; }
Property Value
Type | Description |
---|---|
System.Boolean | True if the document has macros; otherwise, false. |
HTMLImportSettings
Gets or sets the HTML import settings for HTML to Word conversion.
Declaration
public HTMLImportSettings HTMLImportSettings { get; set; }
Property Value
Type |
---|
HTMLImportSettings |
Remarks
This property is not supported in MVC6.
See Also
ImportOptions
Gets or sets a ImportOptions that represents the options to import the source document contents to the destination document. Default value is UseDestinationStyles.
Declaration
public ImportOptions ImportOptions { get; set; }
Property Value
Type |
---|
ImportOptions |
Remarks
This property will not be considered while executing ImportContent method and its overloads in WordDocument class.
Examples
//Creates an new instance of WordDocument class.
WordDocument srcDocument = new WordDocument("SourceTemplate.docx");
// Creates an new instance of WordDocument class.
WordDocument destDocument = new WordDocument("DestinationTemplate.docx");
//Import the contents of source document at the end of destination document with destination styles.
destDocument.ImportOptions = ImportOptions.UseDestinationStyles;
destDocument.Sections.Add(srcDocument.LastSection.Clone());
// Releases the resources occupied by WordDocument instance.
srcDocument.Close();
// Saves the document in the given name and format.
destDocument.Save("Document.docx", FormatType.Docx);
// Releases the resources occupied by WordDocument instance.
destDocument.Close();
'Creates an new instance of WordDocument class.
Dim srcDocument As New WordDocument("SourceTemplate.docx")
' Creates an new instance of WordDocument class.
Dim destDocument As New WordDocument("DestinationTemplate.docx")
'Import the contents of source document at the end of destination document with destination styles.
destDocument.ImportOptions = ImportOptions.UseDestinationStyles
destDocument.Sections.Add(srcDocument.LastSection.Clone())
' Releases the resources occupied by WordDocument instance.
srcDocument.Close()
' Saves the document in the given name and format.
destDocument.Save("Document.docx", FormatType.Docx)
' Releases the resources occupied by WordDocument instance.
destDocument.Close()
ImportStyles
Gets or sets a value indicating whether to import styles with new unique name, if style exist in destination document with same name, type and different formatting. Default value is true
Declaration
public bool ImportStyles { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean | True: if import styles with same name, type and different formatting into destination document by renaming uniquely; otherwise, false. |
Remarks
This property is used for defining styles import behavior in the scenario of style exist in destination document with same name and type, but different formatting. Setting this property to true, styles with same name, type and different formatting will be imported into destination document from source document with new unique name. Setting it to false, styles with same name, type and different formatting will not be imported and instead the document contents will use the existing matched (same name and type) style.
Examples
// Creates an new instance of WordDocument class.
WordDocument srcDocument = new WordDocument();
// Adds a section and a paragraph in the empty document.
srcDocument.EnsureMinimal();
// Sets bold to character format of "Normal" style to differentiate source and destination document.
(srcDocument.Styles.FindByName("Normal") as WParagraphStyle).CharacterFormat.Bold = true;
// Creates an new instance of WordDocument class.
WordDocument destDocument = new WordDocument();
// Adds a section and a paragraph in the empty document.
destDocument.EnsureMinimal();
// Sets false value to exclude importing duplicate styles to destination document.
destDocument.ImportStyles = false;
destDocument.Sections.Add(srcDocument.LastSection.Clone());
// Releases the resources occupied by WordDocument instance.
srcDocument.Close();
// Saves the document in the given name and format.
destDocument.Save("Document.docx", FormatType.Docx);
// Releases the resources occupied by WordDocument instance.
destDocument.Close();
' Creates an new instance of WordDocument class.
Dim srcDocument As New WordDocument()
' Adds a section and a paragraph in the empty document.
srcDocument.EnsureMinimal()
' Sets bold to character format of "Normal" style to differentiate source and destination document.
TryCast(srcDocument.Styles.FindByName("Normal"), WParagraphStyle).CharacterFormat.Bold = True
' Creates an new instance of WordDocument class.
Dim destDocument As New WordDocument()
' Adds a section and a paragraph in the empty document.
destDocument.EnsureMinimal()
' Sets false value to exclude importing duplicate styles to destination document.
destDocument.ImportStyles = False
destDocument.Sections.Add(srcDocument.LastSection.Clone())
' Releases the resources occupied by WordDocument instance.
srcDocument.Close()
' Saves the document in the given name and format.
destDocument.Save("Document.docx", FormatType.Docx)
' Releases the resources occupied by WordDocument instance.
destDocument.Close()
ImportStylesOnTypeMismatch
Gets or sets a value indicating whether to import styles with new unique name, if style exist in destination document with same name and different type. Default value is false
Declaration
public bool ImportStylesOnTypeMismatch { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean | True: if import styles with same name and different type into destination document by renaming uniquely; otherwise, false. |
Remarks
This property is used for defining styles import behavior in the scenario of style exist in destination document with same name, but different type. Setting this property to true, styles with same name and different type will be imported into destination document from source document with new unique name. Setting it to false, styles with same name and different typewill not be imported and instead the document contents will use default style.
Examples
// Creates an new instance of WordDocument class.
WordDocument srcDocument = new WordDocument();
// Adds a section and a paragraph in the empty document.
srcDocument.EnsureMinimal();
// Creates a paragraph style (with name "Test") and adds into source document.
WParagraphStyle paragraphStyle = new WParagraphStyle(srcDocument);
paragraphStyle.Name = "Test";
srcDocument.Styles.Add(paragraphStyle);
// Creates an new instance of WordDocument class.
WordDocument destDocument = new WordDocument();
// Adds a section and a paragraph in the empty document.
destDocument.EnsureMinimal();
// Creates a character style (with same paragraph styel name in source) and adds into destination document.
WCharacterStyle characterStyle = new WCharacterStyle(destDocument);
characterStyle.Name = "Test";
destDocument.Styles.Add(characterStyle);
// Sets true value to include importing duplicate styles (mismatched with types) to destination document.
destDocument.ImportStylesOnTypeMismatch = true;
destDocument.Sections.Add(srcDocument.LastSection.Clone());
// Releases the resources occupied by WordDocument instance.
srcDocument.Close();
// Saves the document in the given name and format.
destDocument.Save("Document.docx", FormatType.Docx);
// Releases the resources occupied by WordDocument instance.
destDocument.Close();
' Creates an new instance of WordDocument class.
Dim srcDocument As New WordDocument()
' Adds a section and a paragraph in the empty document.
srcDocument.EnsureMinimal()
' Creates a paragraph style (with name "Test") and adds into source document.
Dim paragraphStyle As New WParagraphStyle(srcDocument)
paragraphStyle.Name = "Test"
srcDocument.Styles.Add(paragraphStyle)
' Creates an new instance of WordDocument class.
Dim destDocument As New WordDocument()
' Adds a section and a paragraph in the empty document.
destDocument.EnsureMinimal()
' Creates a character style (with same paragraph styel name in source) and adds into destination document.
Dim characterStyle As New WCharacterStyle(destDocument)
characterStyle.Name = "Test"
destDocument.Styles.Add(characterStyle)
' Sets true value to include importing duplicate styles (mismatched with types) to destination document.
destDocument.ImportStylesOnTypeMismatch = True
destDocument.Sections.Add(srcDocument.LastSection.Clone())
' Releases the resources occupied by WordDocument instance.
srcDocument.Close()
' Saves the document in the given name and format.
destDocument.Save("Document.docx", FormatType.Docx)
' Releases the resources occupied by WordDocument instance.
destDocument.Close()
InitialEndnoteNumber
Gets or sets the initial endnote number of the document.
Declaration
public int InitialEndnoteNumber { get; set; }
Property Value
Type |
---|
System.Int32 |
Examples
The following code example demonstrates how to specify the endnote initial number in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the endnote initial number
document.InitialEndnoteNumber = 5;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the endnote initial number
document.InitialEndnoteNumber = 5
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
InitialFootnoteNumber
Gets or sets the initial footnote number of the document.
Declaration
public int InitialFootnoteNumber { get; set; }
Property Value
Type |
---|
System.Int32 |
Examples
The following code example demonstrates how to specify the endnote number format in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the footnote initial number
document.InitialFootnoteNumber = 3;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the footnote initial number
document.InitialFootnoteNumber = 3
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
LastParagraph
Gets the last WParagraph of the document. Read-only.
Declaration
public WParagraph LastParagraph { get; }
Property Value
Type | Description |
---|---|
WParagraph | The WParagraph represents the last paragraph of this WordDocument |
Examples
The following code example demonstrates how to retrieve the last paragraph of the document
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the last paragraph back color as Blue
document.LastParagraph.ParagraphFormat.BackColor = Color.Blue;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the last paragraph back color as Blue
document.LastParagraph.ParagraphFormat.BackColor = Color.Blue
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
LastSection
Gets the last WSection of the document. Read-only.
Declaration
public WSection LastSection { get; }
Property Value
Type | Description |
---|---|
WSection | The WSection represents the last section of this WordDocument |
Examples
The following code example demonstrates how to retrieve the last section of the document
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Retrieve the last section of the document and add new paragraph
document.LastSection.AddParagraph().AppendText("Adding new paragraph to the document");
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Retrieve the last section of the document and add new paragraph
document.LastSection.AddParagraph().AppendText("Adding new paragraph to the document")
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
ListStyles
Gets a ListStyleCollection collection that represents all the list styles in the document. Read-only.
Declaration
public ListStyleCollection ListStyles { get; }
Property Value
Type | Description |
---|---|
ListStyleCollection | All the ListStyle in this WordDocument. |
See Also
MailMerge
Gets a MailMerge object that represents the mail merge functionality of the document. Read-only.
Declaration
public MailMerge MailMerge { get; }
Property Value
Type | Description |
---|---|
MailMerge | The MailMerge instance used to replace the WMergeField with value in the document |
See Also
MdImportSettings
Declaration
public MdImportSettings MdImportSettings { get; }
Property Value
Type |
---|
MdImportSettings |
Properties
Gets the document properties. Read-only.
Declaration
public DocProperties Properties { get; }
Property Value
Type | Description |
---|---|
DocProperties | The DocProperties instance used to specify the document version, form field shading and hyphenation properties of the document |
ProtectionType
Gets or sets the document protection type.
Declaration
public ProtectionType ProtectionType { get; set; }
Property Value
Type | Description |
---|---|
ProtectionType | The ProtectionType will prevent the document from unintentional editing. |
Examples
The following code example demonstrates how to protect the changing of document content.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//protect the document from editing
document.ProtectionType = Syncfusion.DocIO.ProtectionType.AllowOnlyReading;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'protect the document from editing
document.ProtectionType = Syncfusion.DocIO.ProtectionType.AllowOnlyReading
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
ReplaceFirst
Gets or sets a value indicating whether replace only the first occurrence. The default is false.
Declaration
public bool ReplaceFirst { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean | True replace only the first occurrence in the document; false replace all the occurrence. |
Examples
The following code snippet illustrates how to replace the first occurrence of a particular text.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load a template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Set to replace only the first occurrence of a particular text
document.ReplaceFirst = true;
//Find the first occurrence of a particular text in the document
TextSelection selection = document.Find("contents", false, false);
//Initialize text body part
TextBodyPart bodyPart = new TextBodyPart(selection);
//Replace a particular text with the text body part
document.Replace("paragraph", bodyPart, false, true, true);
//Save and close the document
document.Save("Replace.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load a template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Set to replace only the first occurrence of a particular text
document.ReplaceFirst = True
'Find the first occurrence of a particular text in the document
Dim selection As TextSelection = document.Find("contents", False, False)
'Initialize text body part
Dim bodyPart As New TextBodyPart(selection)
'Replace a particular text with the text body part
document.Replace("paragraph", bodyPart, False, True, True)
'Save and close the document
document.Save("Replace.docx", FormatType.Docx)
document.Close()
End Sub
RestartIndexForEndnote
Gets or sets the restart index for the endnotes in the document.
Declaration
public EndnoteRestartIndex RestartIndexForEndnote { get; set; }
Property Value
Type |
---|
EndnoteRestartIndex |
Examples
The following code example demonstrates how to specify the endnote restart index number in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the endnote restart index number
document.RestartIndexForEndnote = EndnoteRestartIndex.RestartForEachSection;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the endnote restart index number
document.RestartIndexForEndnote = EndnoteRestartIndex.RestartForEachSection
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
RestartIndexForFootnotes
Gets or sets the restart index for the footnotes in the document.
Declaration
public FootnoteRestartIndex RestartIndexForFootnotes { get; set; }
Property Value
Type |
---|
FootnoteRestartIndex |
Examples
The following code example demonstrates how to specify the footnote restart index number in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Set the footnote restart index number
document.RestartIndexForFootnotes = FootnoteRestartIndex.RestartForEachPage;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Set the footnote restart index number
document.RestartIndexForFootnotes = FootnoteRestartIndex.RestartForEachPage
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Revisions
Gets a RevisionCollection collection that represents all the revisions in the document. Read-only.
Declaration
public RevisionCollection Revisions { get; }
Property Value
Type | Description |
---|---|
RevisionCollection | A RevisionCollection collection represents all the Revision in this WordDocument |
See Also
SaveOptions
Gets the document save options. Read-only.
Declaration
public SaveOptions SaveOptions { get; }
Property Value
Type | Description |
---|---|
SaveOptions | A SaveOptions that represents the save options for this WordDocument |
See Also
Sections
Gets a WSectionCollection collection that represents all the sections in the document. Read-only.
Declaration
public WSectionCollection Sections { get; }
Property Value
Type | Description |
---|---|
WSectionCollection | A |
See Also
Settings
Gets the compatibility settings of the Word document
Declaration
public Settings Settings { get; }
Property Value
Type | Description |
---|---|
Settings | The compatibility settings. |
Styles
Gets a IStyleCollection collection that represents all the styles in the document. Read-only.
Declaration
public IStyleCollection Styles { get; }
Property Value
Type | Description |
---|---|
IStyleCollection | A IStyleCollection collection represents all the IStyle in this WordDocument |
See Also
TextBoxes
Gets a TextBoxCollection collection that represents all the textboxes in the document. Read-only.
Declaration
public TextBoxCollection TextBoxes { get; set; }
Property Value
Type | Description |
---|---|
TextBoxCollection | A TextBoxCollection collection represents all the WTextBox in this WordDocument. |
See Also
ThrowExceptionsForUnsupportedElements
Gets or sets a value indicating whether to throw exceptions for unsupported elements. The default is false.
Declaration
public bool ThrowExceptionsForUnsupportedElements { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean | True then throw the exception for unsupported elements; otherwise, false. |
TrackChanges
Gets or sets a value indicating whether edits are tracked as revision. The default is false.
Declaration
public bool TrackChanges { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean | True if track changes in on; otherwise, false. |
Examples
The following code snippet shows how to track the edits as revisions in the document
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Enable the TrackChanges to track the edits as revision
document.TrackChanges = true;
//Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Enable the TrackChanges to track the edits as revision
document.TrackChanges = True
'Save and Close the Word document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
UpdateFields
Gets or sets a value indicating whether to update fields in the document.
Declaration
public bool UpdateFields { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean | if update fields, set to |
UpdateStylesOnOpen
Gets or sets a value indicating whether to automatically update styles of the document from the attached template each time the document is opened. Default value is false.
Declaration
public bool UpdateStylesOnOpen { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean | True if the styles of the document are updated to from the attached template;otherwise, false. |
Variables
Gets a DocVariables collection that represents the variables stored in the document. Read-only.
Declaration
public DocVariables Variables { get; }
Property Value
Type | Description |
---|---|
DocVariables | Variables collection contains a Key-Value pair of variable name and its value |
Examples
The following code snippet illustrate how to add a DocVariable field in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
WordDocument document = new WordDocument();
IWSection section = document.AddSection();
IWParagraph paragraph = section.AddParagraph();
paragraph.AppendText("First Name of the customer: ");
//Add the DocVariable field with Variable name and its type
paragraph.AppendField("FirstName", FieldType.FieldDocVariable);
paragraph = section.AddParagraph();
paragraph.AppendText("Last Name of the customer: ");
//Add the DocVariable field with Variable name and its type
paragraph.AppendField("LastName", FieldType.FieldDocVariable);
//Add the value for variable in WordDocument.Variable collection
document.Variables.Add("FirstName", "Jeff");
document.Variables.Add("LastName", "Smith");
//Update the document fields
document.UpdateDocumentFields();
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
Dim document As New WordDocument()
Dim section As IWSection = document.AddSection()
Dim paragraph As IWParagraph = section.AddParagraph()
paragraph.AppendText("First Name of the customer: ")
'Add the DocVariable field with Variable name and its type
paragraph.AppendField("FirstName", FieldType.FieldDocVariable)
paragraph = section.AddParagraph()
paragraph.AppendText("Last Name of the customer: ")
'Add the DocVariable field with Variable name and its type
paragraph.AppendField("LastName", FieldType.FieldDocVariable)
'Add the value for variable in WordDocument.Variable collection
document.Variables.Add("FirstName", "Jeff")
document.Variables.Add("LastName", "Smith")
'Update the document fields
document.UpdateDocumentFields()
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
ViewSetup
Gets or sets the document view type.
Declaration
public ViewSetup ViewSetup { get; }
Property Value
Type | Description |
---|---|
ViewSetup | A ViewSetup represents the display options of this WordDocument in MS Word application |
Watermark
Gets or sets a watermark for the document.
Declaration
public Watermark Watermark { get; set; }
Property Value
Type | Description |
---|---|
Watermark | A text/picture that appears behind the document |
See Also
WidgetCollection
Gets sub widgets
Declaration
protected override IEntityCollectionBase WidgetCollection { get; }
Property Value
Type |
---|
IEntityCollectionBase |
Overrides
Methods
AcceptChanges()
Accepts changes tracked from the moment of last change acceptance.
Declaration
public void AcceptChanges()
Examples
The following code example demonstrates how to accept the tracked changes in the document
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Check whether document has tracked changes
if (document.HasChanges)
//Accept the changes made to the document
document.AcceptChanges();
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Check whether document has tracked changes
If document.HasChanges Then
'Accept the changes made to the document
document.AcceptChanges()
End If
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
AddCharacterStyle(String)
Adds new character style to document.
Declaration
public IWCharacterStyle AddCharacterStyle(string styleName)
Parameters
Type | Name | Description |
---|---|---|
System.String | styleName | A String that contains the name of the newly created WCharacterStyle |
Returns
Type | Description |
---|---|
IWCharacterStyle | The newly created IWCharacterStyle |
AddListStyle(ListType, String)
Adds new list style to document.
Declaration
public ListStyle AddListStyle(ListType listType, string styleName)
Parameters
Type | Name | Description |
---|---|---|
ListType | listType | |
System.String | styleName | A String that contains the name of the newly added list style. |
Returns
Type | Description |
---|---|
ListStyle | The ListStyle this method creates. |
Examples
The following code example demonstrates how to how to create user defined list styles.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Create a new Word document
WordDocument document = new WordDocument();
//Add new section to the document
IWSection section = document.AddSection();
//Add new list style to the document
ListStyle listStyle = document.AddListStyle(ListType.Numbered, "UserdefinedList");
WListLevel levelOne = listStyle.Levels[0];
//Define the follow character, prefix, suffix, start index for level 0
levelOne.FollowCharacter = FollowCharacterType.Tab;
levelOne.NumberPrefix = "(";
levelOne.NumberSufix = ")";
levelOne.PatternType = ListPatternType.LowRoman;
levelOne.StartAt = 1;
levelOne.TabSpaceAfter = 5;
levelOne.NumberAlignment = ListNumberAlignment.Center;
WListLevel levelTwo = listStyle.Levels[1];
//Define the follow character, suffix, pattern, start index for level 1
levelTwo.FollowCharacter = FollowCharacterType.Tab;
levelTwo.NumberSufix = "}";
levelTwo.PatternType = ListPatternType.LowLetter;
levelTwo.StartAt = 2;
//Add new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Add text to the paragraph
paragraph.AppendText("User defined list - Level 0");
//Apply default numbered list style
paragraph.ListFormat.ApplyStyle("UserdefinedList");
//Add second paragraph
paragraph = section.AddParagraph();
paragraph.AppendText("User defined list - Level 1");
//Continue last defined list
paragraph.ListFormat.ContinueListNumbering();
//Increase the level indent
paragraph.ListFormat.IncreaseIndentLevel();
//Save the Word document
document.Save("Sample.docx", FormatType.Docx);
//Close the document
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Create a new Word document
Dim document As New WordDocument()
'Add new section to the document
Dim section As IWSection = document.AddSection()
'Add new list style to the document
Dim listStyle As ListStyle = document.AddListStyle(ListType.Numbered, "UserdefinedList")
Dim levelOne As WListLevel = listStyle.Levels(0)
'Define the follow character, prefix, suffix, start index for level 0
levelOne.FollowCharacter = FollowCharacterType.Tab
levelOne.NumberPrefix = "("
levelOne.NumberSufix = ")"
levelOne.PatternType = ListPatternType.LowRoman
levelOne.StartAt = 1
levelOne.TabSpaceAfter = 5
levelOne.NumberAlignment = ListNumberAlignment.Center
Dim levelTwo As WListLevel = listStyle.Levels(1)
'Define the follow character, suffix, pattern, start index for level 1
levelTwo.FollowCharacter = FollowCharacterType.Tab
levelTwo.NumberSufix = "}"
levelTwo.PatternType = ListPatternType.LowLetter
levelTwo.StartAt = 2
'Add new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Add text to the paragraph
paragraph.AppendText("User defined list - Level 0")
'Apply default numbered list style
paragraph.ListFormat.ApplyStyle("UserdefinedList")
'Add second paragraph
paragraph = section.AddParagraph()
paragraph.AppendText("User defined list - Level 1")
'Continue last defined list
paragraph.ListFormat.ContinueListNumbering()
'Increase the level indent
paragraph.ListFormat.IncreaseIndentLevel()
'Save the Word document
document.Save("Sample.docx", FormatType.Docx)
'Close the document
document.Close()
End Sub
See Also
AddParagraphStyle(String)
Adds a new paragraph style to the document.
Declaration
public IWParagraphStyle AddParagraphStyle(string styleName)
Parameters
Type | Name | Description |
---|---|---|
System.String | styleName | A String that contains the name of the newly created IWParagraphStyle |
Returns
Type | Description |
---|---|
IWParagraphStyle | The IWParagraphStyle this method creates. |
Examples
The following code example demonstrates how to create a custom paragraph style and apply it to a paragraph.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Create a new Word document
WordDocument document = new WordDocument();
//Add new section to the document
IWSection section = document.AddSection();
//Create user defined style
IWParagraphStyle style = document.AddParagraphStyle("User_defined_style");
style.ParagraphFormat.BackColor = Color.LightGray;
style.ParagraphFormat.AfterSpacing = 18f;
style.ParagraphFormat.BeforeSpacing = 18f;
style.ParagraphFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash;
style.ParagraphFormat.Borders.LineWidth = 0.5f;
style.ParagraphFormat.LineSpacing = 15f;
style.CharacterFormat.FontName = "Calibri";
style.CharacterFormat.Italic = true;
//Add new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
IWTextRange text = paragraph.AppendText("A new paragraph style is created and is applied to this paragraph.");
//Apply the new style to paragraph
paragraph.ApplyStyle("User_defined_style");
//Save the Word document
document.Save("Sample.docx", FormatType.Docx);
//Close the document
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Create a new Word document
Dim document As New WordDocument()
'Add new section to the document
Dim section As IWSection = document.AddSection()
'Create user defined style
Dim style As IWParagraphStyle = document.AddParagraphStyle("User_defined_style")
style.ParagraphFormat.BackColor = Color.LightGray
style.ParagraphFormat.AfterSpacing = 18.0F
style.ParagraphFormat.BeforeSpacing = 18.0F
style.ParagraphFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash
style.ParagraphFormat.Borders.LineWidth = 0.5F
style.ParagraphFormat.LineSpacing = 15.0F
style.CharacterFormat.FontName = "Calibri"
style.CharacterFormat.Italic = True
'Add new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
Dim text As IWTextRange = paragraph.AppendText("A new paragraph style is created and is applied to this paragraph.")
'Apply the new style to paragraph
paragraph.ApplyStyle("User_defined_style")
'Save the Word document
document.Save("Sample.docx", FormatType.Docx)
'Close the document
document.Close()
End Sub
See Also
AddSection()
Adds a new section to document.
Declaration
public IWSection AddSection()
Returns
Type | Description |
---|---|
IWSection | The IWSection this method creates. |
Examples
The following code example demonstrates how to add a new section to document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Create a new Word document
WordDocument document = new WordDocument();
//Add new section to the document
IWSection section = document.AddSection();
//Add new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Append the text to the created paragraph
paragraph.AppendText("A new section is added to the document.");
//Save and close the Word document instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Create a new Word document
Dim document As New WordDocument()
'Add new section to the document
Dim section As IWSection = document.AddSection()
'Add new paragraph to the section
Dim paragraph As IWParagraph = section.AddParagraph()
'Append the text to the created paragraph
paragraph.AppendText("A new section is added to the document.")
'Save and close the Word document instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
AddStyle(BuiltinStyle)
Adds the built-in style to the IStyleCollection collection.
Declaration
public IStyle AddStyle(BuiltinStyle builtinStyle)
Parameters
Type | Name | Description |
---|---|---|
BuiltinStyle | builtinStyle | The BuiltinStyle that represents the added built-in style of the document. |
Returns
Type | Description |
---|---|
IStyle | The IStyle this method added to IStyleCollection collection. |
Examples
The following code example demonstrates how to add the built-in style to the document
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Add the built-in style to the document style collection
IStyle style = document.AddStyle(BuiltinStyle.Heading5);
//Apply the added built-in style to the last paragraph of the document
document.LastParagraph.ApplyStyle(style.Name);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Add the built-in style to the document style collection
Dim style As IStyle = document.AddStyle(BuiltinStyle.Heading5)
'Apply the added built-in style to the last paragraph of the document
document.LastParagraph.ApplyStyle(style.Name)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
AddTableStyle(String)
Declaration
public WTableStyle AddTableStyle(string styleName)
Parameters
Type | Name | Description |
---|---|---|
System.String | styleName |
Returns
Type |
---|
WTableStyle |
Clone()
Creates the duplicate copy of this WordDocument instance.
Declaration
public WordDocument Clone()
Returns
Type | Description |
---|---|
WordDocument | The WordDocument this method duplicated. |
Examples
The following code example demonstrates how to clone the Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Open an existing document
WordDocument inputTemplateDoc = new WordDocument("Template.docx");
//Create a clone of Input Template
WordDocument clonedDocument = inputTemplateDoc.Clone();
//Close the input template document instance
inputTemplateDoc.Close();
//Save and Close the cloned document instance
clonedDocument.Save("ClonedDocument.docx");
clonedDocument.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Open an existing document
Dim inputTemplateDoc As New WordDocument(fileName)
'Create a clone of Input Template
Dim clonedDocument As WordDocument = inputTemplateDoc.Clone()
'Close the input template document instance
inputTemplateDoc.Close()
'Save and Close the cloned document instance
clonedDocument.Save("ClonedDocument.docx")
clonedDocument.Close()
End Sub
CloneImpl()
Declaration
protected override object CloneImpl()
Returns
Type |
---|
System.Object |
Overrides
Close()
Release the resources occupied by this WordDocument instance.
Declaration
public void Close()
Compare(WordDocument, String, DateTime, ComparisonOptions)
Compares the specified Word document with the current instance of the WordDocument and marks the difference as tracked changes (revisions).
Declaration
public void Compare(WordDocument document, string author = "Author", DateTime dateTime = null, ComparisonOptions comparisonOptions = null)
Parameters
Type | Name | Description |
---|---|---|
WordDocument | document | The WordDocument to compare. |
System.String | author | The name of the author to use for revisions. If unspecified, it uses the last modified author of the Word document as default. Otherwise, uses the string “Author” if last modified author information not present. |
System.DateTime | dateTime | The date and time to use for revisions. If unspecified, it uses current date and time as default. |
ComparisonOptions | comparisonOptions | Options to use while comparing two Word documents. |
Examples
The following code example demonstrates how to compares the original document with revised document
//Load an existing Word document into DocIO instance
WordDocument originalDocument = new WordDocument("OriginalDocument.docx", FormatType.Docx);
WordDocument revisedDocument = new WordDocument("RevisedDocument.docx", FormatType.Docx);
//Compares the original document with revised document
originalDocument.Compare(revisedDocument, "Nancy Davolio", DateTime.Now.AddDays(-1));
originalDocument.Save("Result.docx", FormatType.Docx);
revisedDocument.Close();
originalDocument.Close();
'Load an existing Word document into DocIO instance
Dim originalDocument As New WordDocument("OriginalDocument.docx", FormatType.Docx)
Dim revisedDocument As New WordDocument("RevisedDocument.docx", FormatType.Docx)
'Compares the original document with revised document
originalDocument.Compare(revisedDocument, "Nancy Davolio", DateTime.Now.AddDays(-1));
originalDocument.Save("Result.docx", FormatType.Docx)
revisedDocument.Close();
originalDocument.Close()
CreateCellFormatImpl()
Implementation of cell format creating
Declaration
protected CellFormat CreateCellFormatImpl()
Returns
Type |
---|
CellFormat |
CreateCharacterFormatImpl()
Implementation of character format creating
Declaration
protected WCharacterFormat CreateCharacterFormatImpl()
Returns
Type | Description |
---|---|
WCharacterFormat | Character format object. |
CreateListFormatImpl(IWParagraph)
Declaration
protected WListFormat CreateListFormatImpl(IWParagraph owner)
Parameters
Type | Name | Description |
---|---|---|
IWParagraph | owner |
Returns
Type |
---|
WListFormat |
CreateListLevelImpl(ListStyle)
Declaration
protected WListLevel CreateListLevelImpl(ListStyle style)
Parameters
Type | Name | Description |
---|---|---|
ListStyle | style |
Returns
Type |
---|
WListLevel |
CreateListStyleImpl()
Declaration
protected ListStyle CreateListStyleImpl()
Returns
Type |
---|
ListStyle |
CreateParagraph()
Creates a new paragraph.
Declaration
public IWParagraph CreateParagraph()
Returns
Type | Description |
---|---|
IWParagraph | The IWParagraph this method created. |
CreateParagraphFormatImpl()
Implementation of paragraph format creating
Declaration
protected WParagraphFormat CreateParagraphFormatImpl()
Returns
Type | Description |
---|---|
WParagraphFormat | Paragraph format object. |
CreateParagraphItem(ParagraphItemType)
Creates a new paragraph item instance.
Declaration
public ParagraphItem CreateParagraphItem(ParagraphItemType itemType)
Parameters
Type | Name | Description |
---|---|---|
ParagraphItemType | itemType | A ParagraphItemType represents the type of paragraph item to create. |
Returns
Type | Description |
---|---|
ParagraphItem | The ParagraphItem this method created. |
CreateTableFormatImpl()
Implementation of table format creating
Declaration
protected RowFormat CreateTableFormatImpl()
Returns
Type | Description |
---|---|
RowFormat | Table format instance |
CreateTextBoxCollectionImpl()
Text
Declaration
protected WTextBoxCollection CreateTextBoxCollectionImpl()
Returns
Type |
---|
WTextBoxCollection |
CreateTextboxFormatImpl()
Implementation of textbox format creating
Declaration
protected WTextBoxFormat CreateTextboxFormatImpl()
Returns
Type | Description |
---|---|
WTextBoxFormat | textbox format object. |
Dispose()
Releases all resources used by the object.
Declaration
public void Dispose()
EncryptDocument(String)
Protects the document with password from unauthorized access.
Declaration
public void EncryptDocument(string password)
Parameters
Type | Name | Description |
---|---|---|
System.String | password | A String used to encrypt the document. |
Remarks
This API is supported from .NET Framework 2.0 and .NET Standard 2.0 onwards.
Examples
The following code example demonstrates how to encrypt the Word document with password.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Open an input Word document
WordDocument document = new WordDocument("Template.docx");
//Encrypt the Word document with a password
document.EncryptDocument("password");
//Save and close the Word document instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Open an input Word document
Dim document As New WordDocument("Template.docx")
'Encrypt the Word document with a password
document.EncryptDocument("password")
'Save and close the Word document instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
EnsureMinimal()
Adds a single IWSection with one IWParagraph, when the document contains no sections.
Declaration
public void EnsureMinimal()
Examples
The following code example demonstrates how to add new section with one paragraph to the empty Word document
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Creates a new Word document.
WordDocument document = new WordDocument();
//Add a section and a paragraph in the empty document
document.EnsureMinimal();
IWParagraph paragraph = document.LastParagraph;
//Append text to the last paragraph of the document
paragraph.AppendText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua");
//Save and close the Word document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Creates a new Word document.
Dim document As New WordDocument()
'Add a section and a paragraph in the empty document
document.EnsureMinimal()
Dim paragraph As IWParagraph = document.LastParagraph
'Append text to the last paragraph of the document
paragraph.AppendText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua")
'Save and close the Word document
document.Save("Comment.docx", FormatType.Docx)
document.Close()
End Sub
Find(String, Boolean, Boolean)
Finds the text based on specified string, taking into the consideration of caseSensitive and wholeWord options.
Declaration
public TextSelection Find(string given, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | A string used to find the text. |
System.Boolean | caseSensitive | Set to true to match the similar case text which specified in the |
System.Boolean | wholeWord | Set to true to match the whole word text which specified in the |
Returns
Type | Description |
---|---|
TextSelection | The TextSelection that contains the found text in the document. |
Examples
The following code example demonstrates how to find a particular text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of a particular text in the document
TextSelection textSelection = document.Find("panda", true, true);
//Get the found text as single text range
WTextRange textRange = textSelection.GetAsOneRange();
//Modify the text
textRange.Text = "Replaced text";
//Set highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow;
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of a particular text in the document
Dim textSelection As TextSelection = document.Find("panda", true, true)
'Get the found text as single text range
Dim textRange As WTextRange = textSelection.GetAsOneRange()
'Modify the text
textRange.Text = "Replaced text"
'Set highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
Find(Regex)
Finds the text based on specified regular expression.
Declaration
public TextSelection Find(Regex pattern)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
Returns
Type | Description |
---|---|
TextSelection | The TextSelection that contains the found text in the document. |
Examples
The following code example demonstrates how to find a particular text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of a particular text in the document
TextSelection textSelection = document.Find(new Regex("panda"));
//Get the found text as single text range
WTextRange textRange = textSelection.GetAsOneRange();
//Modify the text
textRange.Text = "Replaced text";
//Set highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow;
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of a particular text in the document
Dim textSelection As TextSelection = document.Find(New Regex("panda"))
'Get the found text as single text range
Dim textRange As WTextRange = textSelection.GetAsOneRange()
'Modify the text
textRange.Text = "Replaced text"
'Set highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
FindAll(String, Boolean, Boolean)
Finds and returns all entries of the specified string, taking into the consideration of caseSensitive and wholeWord options.
Declaration
public TextSelection[] FindAll(string given, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | A string used to find the text. |
System.Boolean | caseSensitive | Set to true to match the similar case text which specified in the |
System.Boolean | wholeWord | Set to true to match the whole word text which specified in the |
Returns
Type | Description |
---|---|
TextSelection[] | The TextSelection collection that contains all the entries of the found text in the document. |
Examples
The following code example demonstrates how to search a particular text and highlight it.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Find the occurrence of the Word "panda" in the document
TextSelection[] textSelection = document.FindAll("panda", false, true);
//Iterate through each occurrence and highlight it
foreach (TextSelection selection in textSelection)
{
IWTextRange textRange = selection.GetAsOneRange();
textRange.CharacterFormat.HighlightColor = Color.Yellow;
}
//Save and Close the document
document.Save("Result.docx");
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Find the occurrence of the word "panda" in the document
Dim textSelection As TextSelection() = document.FindAll("panda", false, true)
'Iterate through each occurrence and highlight it
For Each selection As TextSelection In textSelection
Dim textRange As IWTextRange = selection.GetAsOneRange()
textRange.CharacterFormat.HighlightColor = Color.Yellow
Next
document.Save("Result.docx")
document.Close()
End Sub
See Also
FindAll(Regex)
Finds and returns all entries of the specified regular expression.
Declaration
public TextSelection[] FindAll(Regex pattern)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
Returns
Type | Description |
---|---|
TextSelection[] | The TextSelection collection that contains all the entries of the found text in the document. |
Examples
The following code example demonstrates how to search a particular text and highlight it.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Find the occurrence of the Word "panda" in the document
TextSelection[] textSelection = document.FindAll(new Regex("panda"));
//Iterate through each occurrence and highlight it
foreach (TextSelection selection in textSelection)
{
IWTextRange textRange = selection.GetAsOneRange();
textRange.CharacterFormat.HighlightColor = Color.Yellow;
}
//Save and Close the document
document.Save("Result.docx");
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Find the occurrence of the word "panda" in the document
Dim textSelection As TextSelection() = document.FindAll(new Regex("panda"))
'Iterate through each occurrence and highlight it
For Each selection As TextSelection In textSelection
Dim textRange As IWTextRange = selection.GetAsOneRange()
textRange.CharacterFormat.HighlightColor = Color.Yellow
Next
document.Save("Result.docx")
document.Close()
End Sub
See Also
FindAllItemsByProperties(EntityType, String[], String[])
Declaration
public List<Entity> FindAllItemsByProperties(EntityType entityType, string[] propertyNames, string[] propertyValues)
Parameters
Type | Name | Description |
---|---|---|
EntityType | entityType | |
System.String[] | propertyNames | |
System.String[] | propertyValues |
Returns
Type |
---|
System.Collections.Generic.List<Entity> |
FindAllItemsByProperty(EntityType, String, String)
Declaration
public List<Entity> FindAllItemsByProperty(EntityType entityType, string propertyName, string propertyValue)
Parameters
Type | Name | Description |
---|---|---|
EntityType | entityType | |
System.String | propertyName | |
System.String | propertyValue |
Returns
Type |
---|
System.Collections.Generic.List<Entity> |
FindItemByProperties(EntityType, String[], String[])
Find an item in a Word document based on the specified property and value.
Declaration
public Entity FindItemByProperties(EntityType entityType, string[] propertyNames, string[] propertyValues)
Parameters
Type | Name | Description |
---|---|---|
EntityType | entityType | EntityType to find in a Word document. |
System.String[] | propertyNames | |
System.String[] | propertyValues |
Returns
Type | Description |
---|---|
Entity | Returns the first occurrence of an item that matches the specified property names and values. |
Examples
//Open an existing Word document.
using(WordDocument document = new WordDocument("Template.docx"))
{
//Find picture by height and width.
WPicture picture = document.FindItemByProperties(EntityType.Picture, new string[] { "Height", "Width" }, new string[] { "100", "50" }) as WPicture;
//Resize the picture.
if (picture != null)
{
picture.Height = 50;
picture.Width = 75;
}
//Save and close the Word document.
document.Save("Sample.docx");
}
'Open an existing Word document.
Dim document As WordDocument = New WordDocument("Template.docx")
'Find pictures by height and width.
Dim picture As WPicture = TryCast(document.FindItemByProperties(EntityType.Picture, New String() {"Height", "Width"}, New String() {"100", "50"}), WPicture)
'Resize the pictures.
If picture IsNot Nothing Then
picture.Height = 50
picture.Width = 75
End If
'Save and close the Word document.
document.Save("Sample.docx")
document.Close()
FindItemByProperty(EntityType, String, String)
Find an item in a Word document based on the specified property and value.
Declaration
public Entity FindItemByProperty(EntityType entityType, string propertyName, string propertyValue)
Parameters
Type | Name | Description |
---|---|---|
EntityType | entityType | EntityType to find in a Word document. |
System.String | propertyName | |
System.String | propertyValue |
Returns
Type | Description |
---|---|
Entity | Returns the first occurrence of an item that matches the specified property and value. |
Examples
//Open an existing Word document.
using(WordDocument document = new WordDocument("Template.docx"))
{
//Find picture by alternative text.
WPicture picture = document.FindItemByProperty(EntityType.Picture, "AlternativeText", "Logo") as WPicture;
//Resize the picture.
if (picture != null)
{
picture.Height = 50;
picture.Width = 75;
}
//Save and close the Word document.
document.Save("Sample.docx");
}
'Open an existing Word document.
Dim document As WordDocument = New WordDocument("Template.docx")
'Find picture by alternative text.
Dim picture As WPicture = TryCast(document.FindItemByProperty(EntityType.Picture, "AlternativeText", "Logo"), WPicture)
'Resize the picture.
If picture IsNot Nothing Then
picture.Height = 50
picture.Width = 75
End If
'Save and close the Word document.
document.Save("Sample.docx")
document.Close()
FindNext(TextBodyItem, String, Boolean, Boolean)
Finds the next entry of the specified text from the specified text body item, taking into the consideration of caseSensitive and wholeWord options.
Declaration
public TextSelection FindNext(TextBodyItem startTextBodyItem, string given, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
TextBodyItem | startTextBodyItem | The TextBodyItem that represents the start body item at which search starts (paragraph or table). |
System.String | given | A string used to find the text. |
System.Boolean | caseSensitive | Set to true to match the similar case text which specified in the |
System.Boolean | wholeWord | Set to true to match the whole word text which specified in the |
Returns
Type | Description |
---|---|
TextSelection | The TextSelection that contains the found text in the document. |
Examples
The following code example demonstrates how to find a particular text and its next occurrence in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load the template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text in the document
TextSelection textSelection = document.Find("as graphical contents", false, true);
//Get the found text as single text range
WTextRange textRange = textSelection.GetAsOneRange();
//Modify the text
textRange.Text = "Replaced text";
//Set highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow;
//Find the next occurrence of a particular text from the previous paragraph
textSelection = document.FindNext(textRange.OwnerParagraph, "paragraph", true, false);
//Get the found text as single text range
WTextRange range = textSelection.GetAsOneRange();
//Set bold formatting
range.CharacterFormat.Bold = true;
//Save and close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load the template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text in the document
Dim textSelection As TextSelection = document.Find("as graphical contents", false, true)
'Get the found text as single text range
Dim textRange As WTextRange = textSelection.GetAsOneRange()
'Modify the text
textRange.Text = "Replaced text"
'Set highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow
'Find the next occurrence of a particular text from the previous paragraph
textSelection = document.FindNext(textRange.OwnerParagraph, "paragraph", true, false)
'Get the found text as single text range
Dim range As WTextRange = textSelection.GetAsOneRange()
'Set bold formatting
range.CharacterFormat.Bold = True
'Save and close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
FindNext(TextBodyItem, Regex)
Finds the next entry of the specified regular expression from the specified text body item.
Declaration
public TextSelection FindNext(TextBodyItem startBodyItem, Regex pattern)
Parameters
Type | Name | Description |
---|---|---|
TextBodyItem | startBodyItem | The TextBodyItem that represents the start body item at which search starts (paragraph or table). |
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
Returns
Type | Description |
---|---|
TextSelection | The TextSelection that contains the found text in the document. |
Examples
The following code example demonstrates how to find a particular text and its next occurrence in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load the template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text in the document
TextSelection textSelection = document.Find(new Regex("as graphical contents"));
//Get the found text as single text range
WTextRange textRange = textSelection.GetAsOneRange();
//Modify the text
textRange.Text = "Replaced text";
//Set highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow;
//Find the next occurrence of a particular text from the previous paragraph
textSelection = document.FindNext(textRange.OwnerParagraph, new Regex("paragraph"));
//Get the found text as single text range
WTextRange range = textSelection.GetAsOneRange();
//Set bold formatting
range.CharacterFormat.Bold = true;
//Save and close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load the template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text in the document
Dim textSelection As TextSelection = document.Find("as graphical contents")
'Get the found text as single text range
Dim textRange As WTextRange = textSelection.GetAsOneRange()
'Modify the text
textRange.Text = "Replaced text"
'Set highlight color
textRange.CharacterFormat.HighlightColor = Color.Yellow
'Find the next occurrence of a particular text from the previous paragraph
textSelection = document.FindNext(textRange.OwnerParagraph, "paragraph")
'Get the found text as single text range
Dim range As WTextRange = textSelection.GetAsOneRange()
'Set bold formatting
range.CharacterFormat.Bold = True
'Save and close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
FindNextSingleLine(TextBodyItem, String, Boolean, Boolean)
Finds the next entry of the specified text from the specified text body item in single-line mode which is extended to several paragraph in the document, taking into the consideration of caseSensitive and wholeWord options.
Declaration
public TextSelection[] FindNextSingleLine(TextBodyItem startTextBodyItem, string given, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
TextBodyItem | startTextBodyItem | The TextBodyItem that represents the start body item at which search starts (paragraph or table). |
System.String | given | A string used to find the text. |
System.Boolean | caseSensitive | Set to true to match the similar case text which specified in the |
System.Boolean | wholeWord | Set to true to match the whole word text which specified in the |
Returns
Type | Description |
---|---|
TextSelection[] | The TextSelection that contains the found text in the document. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to find a particular text and its next occurrence which is extended to several paragraphs in the Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load the template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text extended to several paragraphs in the document
TextSelection[] textSelections = document.FindSingleLine("First paragraph Second paragraph", true, false);
WParagraph paragraph = null;
foreach (TextSelection textSelection in textSelections)
{
//Get the found text as single text range and set highlight color
WTextRange textRange = textSelection.GetAsOneRange();
textRange.CharacterFormat.HighlightColor = Color.YellowGreen;
paragraph = textRange.OwnerParagraph;
}
//Find the next occurrence of a particular text extended to several paragraphs in the document
textSelections = document.FindNextSingleLine(paragraph, "First paragraph Second paragraph", true, false);
foreach (TextSelection textSelection in textSelections)
{
//Get the found text as single text range and set italic formatting
WTextRange text = textSelection.GetAsOneRange();
text.CharacterFormat.Italic = true;
}
//Save and close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load the template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text extended to several paragraphs in the document
Dim textSelections As TextSelection() = document.FindSingleLine("First paragraph Second paragraph", True, False)
Dim paragraph As WParagraph = Nothing
For Each textSelection As TextSelection In textSelections
'Get the found text as single text range and set highlight color
Dim textRange As WTextRange = textSelection.GetAsOneRange()
textRange.CharacterFormat.HighlightColor = Color.YellowGreen
paragraph = textRange.OwnerParagraph
Next
'Find the next occurrence of a particular text extended to several paragraphs in the document
textSelections = document.FindNextSingleLine(paragraph, "First paragraph Second paragraph", True, False)
For Each textSelection As TextSelection In textSelections
'Get the found text as single text range and set italic formatting
Dim text As WTextRange = textSelection.GetAsOneRange()
text.CharacterFormat.Italic = True
Next
'Save and close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
FindNextSingleLine(TextBodyItem, Regex)
Finds the next entry of the specified pattern of text in single-line mode which is extended to several paragraph in the document.
Declaration
public TextSelection[] FindNextSingleLine(TextBodyItem startBodyItem, Regex pattern)
Parameters
Type | Name | Description |
---|---|---|
TextBodyItem | startBodyItem | The TextBodyItem that represents the start body item at which search starts (paragraph or table). |
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
Returns
Type | Description |
---|---|
TextSelection[] | The TextSelection that contains the found text in the document. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to find a particular text and its next occurrence which is extended to several paragraphs in the Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load the template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text extended to several paragraphs in the document
TextSelection[] textSelections = document.FindSingleLine("First paragraph Second paragraph", true, false);
WParagraph paragraph = null;
foreach (TextSelection textSelection in textSelections)
{
//Get the found text as single text range and set highlight color
WTextRange textRange = textSelection.GetAsOneRange();
textRange.CharacterFormat.HighlightColor = Color.YellowGreen;
paragraph = textRange.OwnerParagraph;
}
//Find the next occurrence of a particular text extended to several paragraphs in the document
textSelections = document.FindNextSingleLine(paragraph, new Regex("First paragraph Second paragraph"));
foreach (TextSelection textSelection in textSelections)
{
//Get the found text as single text range and set italic formatting
WTextRange text = textSelection.GetAsOneRange();
text.CharacterFormat.Italic = true;
}
//Save and close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load the template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text extended to several paragraphs in the document
Dim textSelections As TextSelection() = document.FindSingleLine("First paragraph Second paragraph", True, False)
Dim paragraph As WParagraph = Nothing
For Each textSelection As TextSelection In textSelections
'Get the found text as single text range and set highlight color
Dim textRange As WTextRange = textSelection.GetAsOneRange()
textRange.CharacterFormat.HighlightColor = Color.YellowGreen
paragraph = textRange.OwnerParagraph
Next
'Find the next occurrence of a particular text extended to several paragraphs in the document
textSelections = document.FindNextSingleLine(paragraph, new Regex("First paragraph Second paragraph"))
For Each textSelection As TextSelection In textSelections
'Get the found text as single text range and set italic formatting
Dim text As WTextRange = textSelection.GetAsOneRange()
text.CharacterFormat.Italic = True
Next
'Save and close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
FindSingleLine(String, Boolean, Boolean)
Finds the first entry of specified pattern of text in single-line mode which is extended to several paragraph in the document, taking into the consideration of caseSensitive and wholeWord options.
Declaration
public TextSelection[] FindSingleLine(string given, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | A string used to find the text. |
System.Boolean | caseSensitive | Set to true to match the similar case text which specified in the |
System.Boolean | wholeWord | Set to true to match the whole word text which specified in the |
Returns
Type | Description |
---|---|
TextSelection[] | The TextSelection collection that contains the found text in the document. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load the template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text extended to several paragraphs in the document
TextSelection[] textSelections = document.FindSingleLine("First paragraph Second paragraph", true, false);
WParagraph paragraph = null;
foreach (TextSelection textSelection in textSelections)
{
//Get the found text as single text range and set highlight color
WTextRange textRange = textSelection.GetAsOneRange();
textRange.CharacterFormat.HighlightColor = Color.YellowGreen;
paragraph = textRange.OwnerParagraph;
}
//Save and close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load the template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text extended to several paragraphs in the document
Dim textSelections As TextSelection() = document.FindSingleLine("First paragraph Second paragraph", True, False)
Dim paragraph As WParagraph = Nothing
For Each textSelection As TextSelection In textSelections
'Get the found text as single text range and set highlight color
Dim textRange As WTextRange = textSelection.GetAsOneRange()
textRange.CharacterFormat.HighlightColor = Color.YellowGreen
paragraph = textRange.OwnerParagraph
Next
'Save and close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
FindSingleLine(Regex)
Finds the first entry of specified pattern of text in single-line mode which is extended to several paragraph in the document.
Declaration
public TextSelection[] FindSingleLine(Regex pattern)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
Returns
Type | Description |
---|---|
TextSelection[] | The TextSelection collection that contains the found text in the document. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load the template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text extended to several paragraphs in the document
TextSelection[] textSelections = document.FindSingleLine(new Regex("First paragraph Second paragraph"));
WParagraph paragraph = null;
foreach (TextSelection textSelection in textSelections)
{
//Get the found text as single text range and set highlight color
WTextRange textRange = textSelection.GetAsOneRange();
textRange.CharacterFormat.HighlightColor = Color.YellowGreen;
paragraph = textRange.OwnerParagraph;
}
//Save and close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load the template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text extended to several paragraphs in the document
Dim textSelections As TextSelection() = document.FindSingleLine(new Regex("First paragraph Second paragraph"))
Dim paragraph As WParagraph = Nothing
For Each textSelection As TextSelection In textSelections
'Get the found text as single text range and set highlight color
Dim textRange As WTextRange = textSelection.GetAsOneRange()
textRange.CharacterFormat.HighlightColor = Color.YellowGreen
paragraph = textRange.OwnerParagraph
Next
'Save and close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
See Also
GetCrossReferenceItems(ReferenceType)
Gets the list/array of items that can be cross-referenced based on the specified reference type.
Declaration
public List<Entity> GetCrossReferenceItems(ReferenceType refernceType)
Parameters
Type | Name | Description |
---|---|---|
ReferenceType | refernceType | Specifies the type of item you want to insert a cross-reference to. |
Returns
Type | Description |
---|---|
System.Collections.Generic.List<Entity> | The Entity collection that represents the cross reference items in the document. |
Remarks
This method returns the cross reference of Bookmarks items only.
For bookmarks, it returns the entity collections of BookmarkStart only if the bookmark contains proper start and end.
Examples
The following code example demonstrates how to append cross reference for bookmark in Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Get the collection of bookmark start in the word document
List< Entity > items = document.GetCrossReferenceItems(ReferenceType.Bookmark);
if (items.Count > 0)
//Change the first cross reference items owner paragraph back color as YelloGreen
(items[0] as BookmarkStart).OwnerParagraph.ParagraphFormat.BackColor = Color.YellowGreen;
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Get the collection of bookmark start in the word document
Dim items As List(Of Entity) = document.GetCrossReferenceItems(ReferenceType.Bookmark)
If items.Count > 0 Then
'Change the first cross reference items owner paragraph back color as YelloGreen
TryCast(items(0), BookmarkStart).OwnerParagraph.ParagraphFormat.BackColor = Color.YellowGreen
End If
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
GetText()
Returns a string that contains whole document content as text.
Declaration
public string GetText()
Returns
Type | Description |
---|---|
System.String | The text this document contains. |
Remarks
This method is not supported in Silverlight, Windows Phone and Xamarin platforms.
Examples
The following code example demonstrates how to retrieve the Word document contents as a plain text.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load a template document
WordDocument document = new WordDocument("Template.docx");
//Get the document text and close the document
string text = document.GetText();
document.Close();
//Create new Word document
WordDocument newdocument = new WordDocument();
//Add new section
IWSection section = newdocument.AddSection();
//Add new paragraph
IWParagraph paragraph = section.AddParagraph();
//Append the text to the paragraph
paragraph.AppendText(text);
//Save and close the document
newdocument.Save("Sample.docx");
newdocument.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load a template document
Dim document As New WordDocument("Template.docx")
'Get the document text and close the document
Dim text As String = document.GetText()
document.Close()
'Create new Word document
Dim newdocument As New WordDocument()
'Add new section
Dim section As IWSection = newdocument.AddSection()
'Add new paragraph
Dim paragraph As IWParagraph = section.AddParagraph()
'Append the text to the paragraph
paragraph.AppendText(text)
'Save and close the document
newdocument.Save("Sample.docx")
newdocument.Close()
End Sub
ImportContent(IWordDocument)
Import contents and styles from the source document to the destination document.
Declaration
public void ImportContent(IWordDocument doc)
Parameters
Type | Name | Description |
---|---|---|
IWordDocument | doc | The source IWordDocument whose contents are appended at the end of the current WordDocument instance. |
Remarks
When source and destination documents have styles with the same names, then Guid is added as a suffix to the name of the imported styles in the destination document. Due to the above duplication of the same style will increase the file size of the document and also it may lead to Out of memory exception if the machine has some limited amount memory.
To resolve the duplication of the same style from source to destination document, use ImportContent(IWordDocument doc, bool importStyles)
methods with false value for "importStyle" parameter.
Examples
The following code example demonstrates how to import the contents from source document into destination document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Open the source document
WordDocument sourceDocument = new WordDocument("sourceFileName.docx");
//Open the destination document
WordDocument destinationDocument = new WordDocument("targetFileName.docx");
//Import the contents of source document at the end of destination document
destinationDocument.ImportContent(sourceDocument);
//Close the document instance
sourceDocument.Close();
//Save the destination document
destinationDocument.Save("outputFileName.docx", FormatType.Docx);
//Close the document instance
destinationDocument.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Open the source document
Dim sourceDocument As New WordDocument(sourceFileName)
'Open the destination document
Dim destinationDocument As New WordDocument(targetFileName)
'Import the contents of source document at the end of destination document
destinationDocument.ImportContent(sourceDocument)
'Close the document instance
sourceDocument.Close()
'Save the destination document
destinationDocument.Save(outputFileName, FormatType.Docx)
'Close the document instance
destinationDocument.Close()
End Sub
ImportContent(IWordDocument, ImportOptions)
Import contents from the source document to the destination document with various import options.
Declaration
public void ImportContent(IWordDocument doc, ImportOptions importOptions)
Parameters
Type | Name | Description |
---|---|---|
IWordDocument | doc | The source IWordDocument whose contents are appended at the end of the current WordDocument instance. |
ImportOptions | importOptions | The ImportOptions that represents the options to import the source document contents to the destination document. |
Remarks
Essential DocIO supports the importing contents from the source document to the destination document with various import options similar to Microsoft Word copy and paste options. Following are the import options supported by Essential DocIO.
Examples
The following code example demonstrates how to import the contents from source document into destination document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Open the source document
WordDocument sourceDocument = new WordDocument("sourceFileName.docx");
//Open the destination document
WordDocument destinationDocument = new WordDocument("targetFileName.docx");
//Import the contents of source document at the end of destination document
destinationDocument.ImportContent(sourceDocument, ImportOptions.UseDestinationStyles);
//Close the document instance
sourceDocument.Close();
//Save the destination document
destinationDocument.Save("outputFileName.docx", FormatType.Docx);
//Close the document instance
destinationDocument.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Open the source document
Dim sourceDocument As New WordDocument(sourceFileName)
'Open the destination document
Dim destinationDocument As New WordDocument(targetFileName)
'Import the contents of source document at the end of destination document
destinationDocument.ImportContent(sourceDocument, ImportOptions.UseDestinationStyles)
'Close the document instance
sourceDocument.Close()
'Save the destination document
destinationDocument.Save(outputFileName, FormatType.Docx)
'Close the document instance
destinationDocument.Close()
End Sub
ImportContent(IWordDocument, Boolean)
Import contents from the source document to the destination document by specifying whether to import styles that have the same name between the source and destination document.
Declaration
public void ImportContent(IWordDocument doc, bool importStyles)
Parameters
Type | Name | Description |
---|---|---|
IWordDocument | doc | The source IWordDocument whose contents are appended at the end of the current WordDocument instance. |
System.Boolean | importStyles | Set to true to import all the styles from the source document to destination document; otherwise, false. |
Remarks
When importStyles is set to false, all the contents are imported; but, the styles of the source document with style names that do not match with the styles in the destination document are not imported. When the style names match the destination style names, then the same name is applied to the imported contents. This behavior is similar to the Microsoft Word paste option - UseDestinationStyles.
When importStyles is set to true, all the contents and styles of the source document are imported to the destination document. In cases where a style in the source document has the same name as a style in the destination document, "Guid" is added as a suffix to the name of the imported style in order to preserve unique style name. Due to the above duplication of the same style will increase the file size of the document and also it may lead to Out of memory exception if the machine has some limited amount memory.
Examples
The following code example demonstrates how to import the contents from source document into destination document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Open the source document
WordDocument sourceDocument = new WordDocument("sourceFileName.docx");
//Open the destination document
WordDocument destinationDocument = new WordDocument("targetFileName.docx");
//Import the contents of source document at the end of destination document
destinationDocument.ImportContent(sourceDocument, true);
//Close the document instance
sourceDocument.Close();
//Save the destination document
destinationDocument.Save("outputFileName.docx", FormatType.Docx);
//Close the document instance
destinationDocument.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Open the source document
Dim sourceDocument As New WordDocument(sourceFileName)
'Open the destination document
Dim destinationDocument As New WordDocument(targetFileName)
'Import the contents of source document at the end of destination document
destinationDocument.ImportContent(sourceDocument, true)
'Close the document instance
sourceDocument.Close()
'Save the destination document
destinationDocument.Save(outputFileName, FormatType.Docx)
'Close the document instance
destinationDocument.Close()
End Sub
ImportSection(IWSection)
Imports the specified section into the current document.
Declaration
public void ImportSection(IWSection section)
Parameters
Type | Name | Description |
---|---|---|
IWSection | section | The source IWSection whose contents are appended at the end of the current WordDocument instance. |
Examples
The following code example demonstrates how to import the section into the Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Open the source document
WordDocument sourceDocument = new WordDocument("sourceFileName.docx");
//Open the destination document
WordDocument destinationDocument = new WordDocument("targetFileName.docx");
//Import the last section of source document at the end of destination document
destinationDocument.ImportSection(sourceDocument.LastSection);
//Close the document instance
sourceDocument.Close();
//Save the destination document
destinationDocument.Save("outputFileName.docx", FormatType.Docx);
//Close the document instance
destinationDocument.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Open the source document
Dim sourceDocument As New WordDocument(sourceFileName)
'Open the destination document
Dim destinationDocument As New WordDocument(targetFileName)
'Import the last section of source document at the end of destination document
destinationDocument.ImportSection(sourceDocument.LastSection)
'Close the document instance
sourceDocument.Close()
'Save the destination document
destinationDocument.Save(outputFileName, FormatType.Docx)
'Close the document instance
destinationDocument.Close()
End Sub
InitXDLSHolder()
Registers child objects in XDSL holder.
Declaration
protected override void InitXDLSHolder()
Overrides
Open(Stream, FormatType)
Opens an existing document of the specified file format type from the data stream.
Declaration
public void Open(Stream stream, FormatType formatType)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream that contains the data for this WordDocument. |
FormatType | formatType | The file format type of the document to open. |
Examples
The following code example demonstrates how to open an existing document of the specified type from data stream.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Create an new instance of WordDocument class
WordDocument document = new WordDocument();
Stream fileStream = new FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read);
//Open an existing document from file system
document.Open(fileStream, FormatType.Docx);
//Saves the specified document
document.Save("Sample.docx", FormatType.Docx);
//Close the WordDocument instance
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Create an new instance of WordDocument class
Dim document As New WordDocument()
Dim fileStream As Stream = New FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read)
'Open an existing document from file system
document.Open(fileStream, FormatType.Docx)
'Saves the specified document
document.Save("Sample.docx", FormatType.Docx)
'Close the WordDocument instance
document.Close()
End Sub
Open(Stream, FormatType, String)
Opens an existing document of the specified file format type from the data stream, which is protected with password.
Declaration
public void Open(Stream stream, FormatType formatType, string password)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream that contains the data for this WordDocument. |
FormatType | formatType | The file format type of the document to open. |
System.String | password | The password used to decrypt the document. |
Remarks
This API is supported from .NET Framework 2.0 and .NET Standard 2.0 onwards.
Examples
The following code example demonstrates how to open a protected document of the specified type from data stream.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Create an new instance of WordDocument class
WordDocument document = new WordDocument();
Stream fileStream = new FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read);
//Open an existing document from file system
document.Open(fileStream, FormatType.Docx, "password");
//Saves the specified document
document.Save("Sample.docx", FormatType.Docx);
//Close the WordDocument instance
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Create an new instance of WordDocument class
Dim document As New WordDocument()
Dim fileStream As Stream = New FileStream("Sample.docx", FileMode.Open, FileAccess.Read, FileShare.Read)
'Open an existing document from file system
document.Open(fileStream, FormatType.Docx, "password")
'Saves the specified document
document.Save("Sample.docx", FormatType.Docx)
'Close the WordDocument instance
document.Close()
End Sub
OpenAsync(Stream, FormatType)
Opens an existing document of the specified file format type asynchronously from the data stream.
Declaration
public Task<bool> OpenAsync(Stream stream, FormatType formatType)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream that contains the data for this WordDocument. |
FormatType | formatType | The file format type of the document to open. |
Returns
Type | Description |
---|---|
System.Threading.Tasks.Task<System.Boolean> | A task that represents the asynchronous open operation. |
Examples
The following code example demonstrates how to open an existing document from stream.
private async void Button_Click(object sender, RoutedEventArgs e)
{
Assembly execAssem = typeof(MainPage).GetTypeInfo().Assembly;
WordDocument document = new WordDocument();
Stream inputStream = execAssem.GetManifestResourceStream("Template.docx");
// Open an existing template document.
await document.OpenAsync(inputStream, FormatType.Docx);
MemoryStream stream = new MemoryStream();
//Save the document to stream
await document.SaveAsync(stream, FormatType.Docx);
//Close the document
document.Close();
}
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim execAssem As Assembly = GetType(MainPage).GetTypeInfo().Assembly
Dim document As New WordDocument()
Dim inputStream As Stream = execAssem.GetManifestResourceStream("Template.docx")
' Open an existing template document.
Await document.OpenAsync(inputStream, FormatType.Docx)
Dim stream As New MemoryStream()
'Save the document to stream
Await document.SaveAsync(stream, FormatType.Docx)
'Close the document
document.Close()
End Sub
OpenAsync(Stream, FormatType, String)
Opens an existing document of the specified file format type asynchronously from the data stream, which is protected with password.
Declaration
public Task<bool> OpenAsync(Stream stream, FormatType formatType, string password)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream that contains the data for this WordDocument. |
FormatType | formatType | The file format type of the document to open. |
System.String | password | The password used to decrypt the document. |
Returns
Type | Description |
---|---|
System.Threading.Tasks.Task<System.Boolean> | A task that represents the asynchronous open operation. |
Examples
The following code example demonstrates how to open an existing document from stream.
private async void Button_Click(object sender, RoutedEventArgs e)
{
Assembly execAssem = typeof(MainPage).GetTypeInfo().Assembly;
WordDocument document = new WordDocument();
Stream inputStream = execAssem.GetManifestResourceStream("Template.docx");
// Open an existing template document.
await document.OpenAsync(inputStream, FormatType.Docx, "password");
MemoryStream stream = new MemoryStream();
//Save the document to stream
await document.SaveAsync(stream, FormatType.Docx);
//Close the document
document.Close();
}
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim execAssem As Assembly = GetType(MainPage).GetTypeInfo().Assembly
Dim document As New WordDocument()
Dim inputStream As Stream = execAssem.GetManifestResourceStream("Template.docx")
' Open an existing template document.
Await document.OpenAsync(inputStream, FormatType.Docx, "password")
Dim stream As New MemoryStream()
'Save the document to stream
Await document.SaveAsync(stream, FormatType.Docx)
'Close the document
document.Close()
End Sub
OpenAsync(StorageFile)
Declaration
public Task<bool> OpenAsync(StorageFile file)
Parameters
Type | Name | Description |
---|---|---|
Windows.Storage.StorageFile | file |
Returns
Type |
---|
System.Threading.Tasks.Task<System.Boolean> |
OpenAsync(StorageFile, FormatType)
Declaration
public Task<bool> OpenAsync(StorageFile file, FormatType formatType)
Parameters
Type | Name | Description |
---|---|---|
Windows.Storage.StorageFile | file | |
FormatType | formatType |
Returns
Type |
---|
System.Threading.Tasks.Task<System.Boolean> |
OpenAsync(StorageFile, FormatType, String)
Declaration
public Task<bool> OpenAsync(StorageFile file, FormatType formatType, string password)
Parameters
Type | Name | Description |
---|---|---|
Windows.Storage.StorageFile | file | |
FormatType | formatType | |
System.String | password |
Returns
Type |
---|
System.Threading.Tasks.Task<System.Boolean> |
Protect(ProtectionType)
Protects the document from unintentional editing.
Declaration
public void Protect(ProtectionType type)
Parameters
Type | Name | Description |
---|---|---|
ProtectionType | type | The type of protection to be applied. |
Examples
The following code example demonstrates how to protect the document from unintentional editing.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Apply the protection to the document
document.Protect(ProtectionType.AllowOnlyComments);
//Save and close the document instances
document.Save("Sample.docx");
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Apply the protection to the document
document.Protect(ProtectionType.AllowOnlyComments)
'Save and close the document instances
document.Save("Sample.docx")
document.Close()
End Sub
Protect(ProtectionType, String)
Protects the document from unintentional editing with secure password.
Declaration
public void Protect(ProtectionType type, string password)
Parameters
Type | Name | Description |
---|---|---|
ProtectionType | type | The type of protection to be applied. |
System.String | password | The password used for protection. |
Remarks
This method is not supported in MVC6 and Xamarin platforms.
Examples
The following code example demonstrates how to protect the document from unintentional editing.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx", "password");
//Apply the protection to the document
document.Protect(ProtectionType.AllowOnlyComments);
//Save and close the document instances
document.Save("Sample.docx");
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Apply the protection to the document
document.Protect(ProtectionType.AllowOnlyComments, "password")
'Save and close the document instances
document.Save("Sample.docx")
document.Close()
End Sub
ReadXmlAttributes(IXDLSAttributeReader)
Reads object data from xml attributes.
Declaration
protected override void ReadXmlAttributes(IXDLSAttributeReader reader)
Parameters
Type | Name | Description |
---|---|---|
IXDLSAttributeReader | reader | The IXDLSAttributeReader object. |
Overrides
ReadXmlContent(IXDLSContentReader)
Reads object data from xml attributes.
Declaration
protected override bool ReadXmlContent(IXDLSContentReader reader)
Parameters
Type | Name | Description |
---|---|---|
IXDLSContentReader | reader | The IXDLSContentReader object. |
Returns
Type | Description |
---|---|
System.Boolean | The value indicating the presence of xml content. |
Overrides
RejectChanges()
Rejects changes tracked from the moment of last change acceptance.
Declaration
public void RejectChanges()
Examples
The following code example demonstrates how to reject the tracked changes in the document
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Template.docx");
//Check whether document has tracked changes
if (document.HasChanges)
//Reject the changes made to the document
document.RejectChanges();
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Template.docx")
'Check whether document has tracked changes
If document.HasChanges Then
'Reject the changes made to the document
document.RejectChanges()
End If
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
RemoveEncryption()
Removes the encryption from the document.
Declaration
public void RemoveEncryption()
Remarks
This API is supported from .NET Framework 2.0 and .NET Standard 2.0 onwards.
Examples
The following code example demonstrates how to remove encrypt from the Word document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Open an input Word document
WordDocument document = new WordDocument("Template.docx");
//Remove the encryption from document
document.RemoveEncryption();
//Save and close the Word document instance
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Open an input Word document
Dim document As New WordDocument("Template.docx")
'Remove the encryption from document
document.RemoveEncryption();
'Save and close the Word document instance
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
RemoveMacros()
Removes the macros in the document.
Declaration
public void RemoveMacros()
Remarks
This method removes the macros from DOCM and DOTM format files.
Examples
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load the document with macros
WordDocument document = new WordDocument("Sample.docm");
//Check whether the document has macros and remove them
if (document.HasMacros)
document.RemoveMacros();
//Save the document
document.Save("Sample.docx", FormatType.Docx);
//Close the document
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load the document with macros
Dim document As New WordDocument("Sample.docm")
'Check whether the document has macros and remove them
If document.HasMacros Then
document.RemoveMacros()
End If
'Save the document
document.Save("Sample.docx", FormatType.Docx)
'Close the document
document.Close()
End Sub
Replace(String, IWordDocument, Boolean, Boolean)
Replaces all entries of given string in the document with another Word document, taking into consideration case sensitive, whole word options.
Declaration
public int Replace(string given, IWordDocument replaceDoc, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
IWordDocument | replaceDoc | The Word document to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | Set to true to match the whole word of the text similar to specified in the |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Load the another existing Word document to replace
WordDocument replaceDocument = new WordDocument("Replace.docx");
//Replace all occurrence of a particular regular expression with the another document and close the document
document.Replace("Giant panda", replaceDocument, true, false);
replaceDocument.Close();
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Load the another existing Word document to replace
Dim replaceDocument As New WordDocument("Replace.docx")
'Replace all occurrence of a particular regular expression with the another document and close the document
document.Replace("Giant panda", replaceDocument, True, False)
replaceDocument.Close();
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(String, IWordDocument, Boolean, Boolean, Boolean)
Replaces all entries of given string in the document with another Word document, taking into consideration case sensitive, whole word and formatting options.
Declaration
public int Replace(string given, IWordDocument replaceDoc, bool caseSensitive, bool wholeWord, bool saveFormatting)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
IWordDocument | replaceDoc | The Word document to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | Set to true to match the whole word of the text similar to specified in the |
System.Boolean | saveFormatting | Set to true to save source formatting; otherwise, false. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Load the another existing Word document to replace
WordDocument replaceDocument = new WordDocument("Replace.docx");
//Replace all occurrence of a particular regular expression with the another document and close the document
document.Replace("Giant panda", replaceDocument, true, false, true);
replaceDocument.Close();
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Load the another existing Word document to replace
Dim replaceDocument As New WordDocument("Replace.docx")
'Replace all occurrence of a particular regular expression with the another document and close the document
document.Replace("Giant panda", replaceDocument, True, False, True)
replaceDocument.Close();
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(String, TextBodyPart, Boolean, Boolean)
Replaces all entries of given string in the document with TextBodyPart, taking into consideration case sensitive, whole word options.
Declaration
public int Replace(string given, TextBodyPart bodyPart, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
TextBodyPart | bodyPart | The text body part to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | if it specifies whole word, set to |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of the regular expression
TextSelection selection = document.Find(new Regex("Panda"));
//Initialize text body part
TextBodyPart bodyPart = new TextBodyPart(selection);
//Replace a particular text with the text body part
document.Replace("Giant panda", bodyPart, true, false);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of the regular expression
Dim selection As TextSelection = document.Find(New Regex("Panda"))
'Initialize text body part
Dim bodyPart As New TextBodyPart(selection)
'Replace a particular text with the text body part
document.Replace("Giant panda", bodyPart, True, False)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(String, TextBodyPart, Boolean, Boolean, Boolean)
Replaces all entries of given string in the document with TextBodyPart, taking into consideration case sensitive, whole word and formatting options.
Declaration
public int Replace(string given, TextBodyPart bodyPart, bool caseSensitive, bool wholeWord, bool saveFormatting)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
TextBodyPart | bodyPart | The text body part to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | Set to true to match the whole word of the text similar to specified in the |
System.Boolean | saveFormatting | Set to true to save source formatting; otherwise, false. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of the regular expression
TextSelection selection = document.Find(new Regex("Panda"));
//Initialize text body part
TextBodyPart bodyPart = new TextBodyPart(selection);
//Replace a particular text with the text body part
document.Replace("Giant panda", bodyPart, true, false, true);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of the regular expression
Dim selection As TextSelection = document.Find(New Regex("Panda"))
'Initialize text body part
Dim bodyPart As New TextBodyPart(selection)
'Replace a particular text with the text body part
document.Replace("Giant panda", bodyPart, True, False, True)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(String, TextSelection, Boolean, Boolean)
Replaces all entries of given string in the document with TextSelection, taking into consideration case sensitive and whole word options.
Declaration
public int Replace(string given, TextSelection textSelection, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
TextSelection | textSelection | The TextSelection specifies the text to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | Set to true to match the whole word of the text similar to specified in the |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of the regular expression
TextSelection selection = document.Find(new Regex("Panda"));
//Replace all occurrence of a particular regular expression with the text selection in the document
document.Replace("Giant panda", selection, true, false);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of the regular expression
Dim selection As TextSelection = document.Find(New Regex("Panda"))
'Replace all occurrence of a particular regular expression with the text selection in the document
document.Replace("Giant panda", selection, True, False)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(String, TextSelection, Boolean, Boolean, Boolean)
Replaces all entries of given string in the document with TextSelection, taking into consideration case sensitive, whole word and formatting options.
Declaration
public int Replace(string given, TextSelection textSelection, bool caseSensitive, bool wholeWord, bool saveFormatting)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
TextSelection | textSelection | The TextSelection specifies the text to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | Set to true to match the whole word of the text similar to specified in the |
System.Boolean | saveFormatting | Set to true if to save source formatting; otherwise, false. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of the regular expression
TextSelection selection = document.Find(new Regex("Panda"));
//Replace all occurrence of a particular regular expression with the text selection in the document
document.Replace("Giant panda", selection, true, false, true);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of the regular expression
Dim selection As TextSelection = document.Find(New Regex("Panda"))
'Replace all occurrence of a particular regular expression with the text selection in the document
document.Replace("Giant panda", selection, True, False, False)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(String, String, Boolean, Boolean)
Replaces all entries of given string in the document with replace string, taking into consideration of case sensitive and whole word options.
Declaration
public int Replace(string given, string replace, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
System.String | replace | The string specifies the text to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | Set to true to match the whole word of the text similar to specified in the |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Replace all occurrence of a particular text in the document
document.Replace("Paragraph","paragraph", false, true);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Replace all occurrence of a particular text in the document
document.Replace("Paragraph", "paragraph", False, True)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(Regex, IWordDocument, Boolean)
Replaces all entries of given regular expression in the document with the another word document along with its formatting.
Declaration
public int Replace(Regex pattern, IWordDocument replaceDoc, bool saveFormatting)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
IWordDocument | replaceDoc | The Word document to replace. |
System.Boolean | saveFormatting | Set to true to save source formatting; otherwise, false. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Load the another existing Word document to replace
WordDocument replaceDocument = new WordDocument("Replace.docx");
//Replace all occurrence of a particular regular expression with the another document and close the document
document.Replace(new Regex("Giant panda"), replaceDocument, true);
replaceDocument.Close();
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Load the another existing Word document to replace
Dim replaceDocument As New WordDocument("Replace.docx")
'Replace all occurrence of a particular regular expression with the another document and close the document
document.Replace(New Regex("Giant panda"), replaceDocument, True)
replaceDocument.Close();
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(Regex, TextBodyPart)
Replaces all entries of given regular expression in the document with the TextBodyPart.
Declaration
public int Replace(Regex pattern, TextBodyPart bodyPart)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
TextBodyPart | bodyPart | The text body part to replace. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of the regular expression
TextSelection selection = document.Find(new Regex("Panda"));
//Initialize text body part
TextBodyPart bodyPart = new TextBodyPart(selection);
//Replace a particular text with the text body part
document.Replace(new Regex("Giant panda"), bodyPart);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of the regular expression
Dim selection As TextSelection = document.Find(New Regex("Panda"))
'Initialize text body part
Dim bodyPart As New TextBodyPart(selection)
'Replace a particular text with the text body part
document.Replace(New Regex("Giant panda"), bodyPart)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(Regex, TextBodyPart, Boolean)
Replaces all entries of given regular expression in the document with the TextBodyPart along with its formatting.
Declaration
public int Replace(Regex pattern, TextBodyPart bodyPart, bool saveFormatting)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
TextBodyPart | bodyPart | The text body part to replace. |
System.Boolean | saveFormatting | Set to true to save source formatting; otherwise, false. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of the regular expression
TextSelection selection = document.Find(new Regex("Panda"));
//Initialize text body part
TextBodyPart bodyPart = new TextBodyPart(selection);
//Replace a particular text with the text body part
document.Replace(new Regex("Giant panda"), bodyPart, true);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of the regular expression
Dim selection As TextSelection = document.Find(New Regex("Panda"))
'Initialize text body part
Dim bodyPart As New TextBodyPart(selection)
'Replace a particular text with the text body part
document.Replace(New Regex("Giant panda"), bodyPart, True)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(Regex, TextSelection)
Replaces the specified regular expression with a TextSelection in the document.
Declaration
public int Replace(Regex pattern, TextSelection textSelection)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
TextSelection | textSelection | The TextSelection specifies the text to replace. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of the regular expression
TextSelection selection = document.Find(new Regex("Panda"));
//Replace all occurrence of a particular regular expression with the text selection in the document
document.Replace(new Regex("Giant panda"), selection);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of the regular expression
Dim selection As TextSelection = document.Find(New Regex("Panda"))
'Replace all occurrence of a particular regular expression with the text selection in the document
document.Replace(New Regex("Giant panda"), selection)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(Regex, TextSelection, Boolean)
Replaces all entries of given regular expression in the document with the TextSelection along with its formatting.
Declaration
public int Replace(Regex pattern, TextSelection textSelection, bool saveFormatting)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
TextSelection | textSelection | The TextSelection specifies the text to replace. |
System.Boolean | saveFormatting | Set to true to save source formatting; otherwise, false. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the document.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Find the first occurrence of the regular expression
TextSelection selection = document.Find(new Regex("Panda"));
//Replace all occurrence of a particular regular expression with the text selection in the document
document.Replace(new Regex("Giant panda"), selection, true);
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Find the first occurrence of the regular expression
Dim selection As TextSelection = document.Find(New Regex("Panda"))
'Replace all occurrence of a particular regular expression with the text selection in the document
document.Replace(New Regex("Giant panda"), selection, True)
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
Replace(Regex, String)
Replaces all entries of the given System.Text.RegularExpressions.Regex with the replace string.
Declaration
public int Replace(Regex pattern, string replace)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
System.String | replace | The string specifies the text to replace. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Examples
The following code example demonstrates how to replace all the entries of a text in the paragraph.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx");
//Replace all occurrence of a particular text in the document
document.Replace(new Regex("Paragraph"),"paragraph");
//Save and Close the document
document.Save("Sample.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx")
'Replace all occurrence of a particular text in the document
document.Replace(New Regex("Paragraph"), "paragraph")
'Save and Close the document
document.Save("Sample.docx", FormatType.Docx)
document.Close()
End Sub
ReplaceSingleLine(String, TextBodyPart, Boolean, Boolean)
Replaces all entries of given string which is extended to several paragraphs in the document with TextBodyPart, taking into consideration case sensitive, whole word options.
Declaration
public int ReplaceSingleLine(string given, TextBodyPart replacement, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
TextBodyPart | replacement | The text body part to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | if it specifies whole word, set to |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to replace the text extended to several paragraphs with TextBodyPart.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load a template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text in the document
TextSelection selection = document.Find("contents", false, false);
//Initialize text body part
TextBodyPart bodyPart = new TextBodyPart(selection);
//Replace a particular text with the text body part
document.ReplaceSingleLine("First paragraph Second paragraph", bodyPart, true, false);
//Save and close the document
document.Save("Replace.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load a template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text in the document
Dim selection As TextSelection = document.Find("contents", False, False)
'Initialize text body part
Dim bodyPart As New TextBodyPart(selection)
'Replace a particular text with the text body part
document.ReplaceSingleLine("First paragraph Second paragraph", bodyPart, True, False)
'Save and close the document
document.Save("Replace.docx", FormatType.Docx)
document.Close()
End Sub
ReplaceSingleLine(String, TextSelection, Boolean, Boolean)
Replaces all entries of given string which is extended to several paragraph in the document with TextSelection, taking into consideration case sensitive and whole word options.
Declaration
public int ReplaceSingleLine(string given, TextSelection replacement, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
TextSelection | replacement | The TextSelection specifies the text to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | Set to true to match the whole word of the text similar to specified in the |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to replace the text extended to several paragraphs with another text.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load a template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text in the document
TextSelection selection = document.Find("contents", false, false);
//Replace the text extended to two paragraphs with text selection
document.ReplaceSingleLine("First paragraph Second paragraph", selection, true, false);
//Save and close the document
document.Save("Replace.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load a template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text in the document
Dim selection As TextSelection = document.Find("contents", False, False)
'Replace the text extended to two paragraphs with text selection
document.ReplaceSingleLine("First paragraph Second paragraph", selection, True, False)
'Save and close the document
document.Save("Replace.docx", FormatType.Docx)
document.Close()
End Sub
ReplaceSingleLine(String, String, Boolean, Boolean)
Replaces all entries of given string which is extended to several paragraphs in the document with replace string, taking into consideration of case sensitive and whole word options.
Declaration
public int ReplaceSingleLine(string given, string replace, bool caseSensitive, bool wholeWord)
Parameters
Type | Name | Description |
---|---|---|
System.String | given | The string represents the text to be found. |
System.String | replace | The string specifies the text to replace. |
System.Boolean | caseSensitive | Set to true to match the case of the text similar to specified in the |
System.Boolean | wholeWord | Set to true to match the whole word of the text similar to specified in the |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to replace the text extended to several paragraphs with simple text.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load a template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Replace the text extended to two paragraphs with simple text
document.ReplaceSingleLine("First paragraph Second paragraph", "Replaced paragraph", true, false);
//Save and close the document
document.Save("Replace.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load a template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Replace the text extended to two paragraphs with simple text
document.ReplaceSingleLine("First paragraph Second paragraph", "Replaced paragraph", True, False)
'Save and close the document
document.Save("Replace.docx", FormatType.Docx)
document.Close()
End Sub
ReplaceSingleLine(Regex, TextBodyPart)
Replaces all entries of given regular expression text which is extended to several paragraph in the document with the TextBodyPart.
Declaration
public int ReplaceSingleLine(Regex pattern, TextBodyPart replacement)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
TextBodyPart | replacement | The text body part to replace. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to replace the text extended to several paragraphs with TextBodyPart.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load a template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text in the document
TextSelection selection = document.Find("contents", false, false);
//Initialize text body part
TextBodyPart bodyPart = new TextBodyPart(selection);
//Replace a particular text with the text body part
document.ReplaceSingleLine(new Regex("First paragraph Second paragraph"), bodyPart);
//Save and close the document
document.Save("Replace.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load a template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text in the document
Dim selection As TextSelection = document.Find("contents", False, False)
'Initialize text body part
Dim bodyPart As New TextBodyPart(selection)
'Replace a particular text with the text body part
document.ReplaceSingleLine(New Regex("First paragraph Second paragraph"), bodyPart)
'Save and close the document
document.Save("Replace.docx", FormatType.Docx)
document.Close()
End Sub
ReplaceSingleLine(Regex, TextSelection)
Replaces all entries of given regular expression text which is extended to several paragraph in the document with the TextSelection.
Declaration
public int ReplaceSingleLine(Regex pattern, TextSelection replacement)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
TextSelection | replacement | The text selection to replace. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to replace the text extended to several paragraphs with another text.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load a template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Find the first occurrence of a particular text in the document
TextSelection selection = document.Find("contents", false, false);
//Replace the text extended to two paragraphs with text selection
document.ReplaceSingleLine(new Regex("First paragraph Second paragraph"), selection);
//Save and close the document
document.Save("Replace.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load a template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Find the first occurrence of a particular text in the document
Dim selection As TextSelection = document.Find("contents", False, False)
'Replace the text extended to two paragraphs with text selection
document.ReplaceSingleLine(New Regex("First paragraph Second paragraph"), selection)
'Save and close the document
document.Save("Replace.docx", FormatType.Docx)
document.Close()
End Sub
ReplaceSingleLine(Regex, String)
Replaces all entries of the specified pattern text, which is extended to several paragraph, with replace text.
Declaration
public int ReplaceSingleLine(Regex pattern, string replace)
Parameters
Type | Name | Description |
---|---|---|
System.Text.RegularExpressions.Regex | pattern | The System.Text.RegularExpressions.Regex used to find the text. |
System.String | replace | The string specifies the text to replace. |
Returns
Type | Description |
---|---|
System.Int32 | The integer that represents the count of the replacements made. |
Remarks
This API not works for the text inside anInlineContentControl.
Examples
The following code example demonstrates how to replace the text extended to several paragraphs with simple text.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load a template document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Replace the text extended to two paragraphs with simple text
document.ReplaceSingleLine(new Regex("First paragraph Second paragraph"), "Replaced paragraph");
//Save and close the document
document.Save("Replace.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load a template document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Replace the text extended to two paragraphs with simple text
document.ReplaceSingleLine(New Regex("First paragraph Second paragraph"), "Replaced paragraph")
'Save and close the document
document.Save("Replace.docx", FormatType.Docx)
document.Close()
End Sub
ResetFindNext()
Resets the find next of WordDocument.
Declaration
public void ResetFindNext()
Save(Stream, FormatType)
Saves this WordDocument to the specified stream in the specified file format type.
Declaration
public void Save(Stream stream, FormatType formatType)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | The Stream where the document will be saved. |
FormatType | formatType | The format in which the document is saved. |
Examples
The following code example demonstrates how to save the document to MemoryStream
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
MemoryStream stream = new MemoryStream();
//Save the document to stream
document.Save(stream, FormatType.Docx);
//Close the document
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
Dim stream As New MemoryStream()
'Save the document to stream
document.Save(stream, FormatType.Docx)
'Close the document
document.Close()
End Sub
SaveAsync(Stream, FormatType)
Saves the document into stream in specified format type.
Declaration
public Task<bool> SaveAsync(Stream stream, FormatType formatType)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream where the document will be saved. |
FormatType | formatType | The file format type in which the document will be saved. |
Returns
Type | Description |
---|---|
System.Threading.Tasks.Task<System.Boolean> | A task that represents the asynchronous save operation. |
Examples
The following code demonstrates how to save a document to MemoryStream.
private async void Button_Click(object sender, RoutedEventArgs e)
{
//Open the document using file open picker
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.List;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".docx");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
WordDocument document = new WordDocument();
//load the opened storage file in WordDocument instance
await document.OpenAsync(file);
MemoryStream stream = new MemoryStream();
//Save the document to stream
await document.SaveAsync(stream, FormatType.Docx);
//Close the document
document.Close();
}
}
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
'Open the document using file open picker
Dim openPicker As New FileOpenPicker()
openPicker.ViewMode = PickerViewMode.List
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
openPicker.FileTypeFilter.Add(".docx")
Dim file As StorageFile = Await openPicker.PickSingleFileAsync()
If file IsNot Nothing Then
Dim document As New WordDocument()
'load the opened storage file in WordDocument instance
Await document.OpenAsync(file)
Dim stream As New MemoryStream()
'Save the document to stream
Await document.SaveAsync(stream, FormatType.Docx)
'Close the document
document.Close()
End If
End Sub
SaveAsync(StorageFile, FormatType)
Declaration
public Task<bool> SaveAsync(StorageFile file, FormatType formatType)
Parameters
Type | Name | Description |
---|---|---|
Windows.Storage.StorageFile | file | |
FormatType | formatType |
Returns
Type |
---|
System.Threading.Tasks.Task<System.Boolean> |
SaveTxt(Stream, Encoding)
Saves this WordDocumentas text (.txt) in Stream with specified encoding.
Declaration
public void SaveTxt(Stream stream, Encoding encoding)
Parameters
Type | Name | Description |
---|---|---|
System.IO.Stream | stream | A System.IO.Stream to save this WordDocument. |
System.Text.Encoding | encoding | The character encoding to use. |
Examples
The following code example demonstrates how to convert the Word document into text file.
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
MemoryStream stream = new MemoryStream();
//Save the document as Text file
document.SaveTxt(stream, Encoding.ASCII);
//Close the document
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document
Dim document As New WordDocument("Template.docx", FormatType.Docx)
Dim stream As New MemoryStream()
'Save the document as Text file
document.SaveTxt(stream, Encoding.ASCII)
'Close the document
document.Close()
End Sub
UpdateAlternateChunks()
Updates the Alternate chunks present in the Word document
Declaration
public void UpdateAlternateChunks()
Examples
The following code example demonstrates how to update the Alternate chunks present in Word document
private void Button1_Click(System.Object sender, System.EventArgs e)
{
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Input.docx", FormatType.Docx);
//Updates the Alternate chunks present in a document.
document.UpdateAlternateChunks();
document.Save("Result.docx", FormatType.Docx);
document.Close();
}
Private Sub button_Click(sender As Object, e As EventArgs)
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Input.docx", FormatType.Docx)
'Updates the Alternate chunks present in a document.
document.UpdateAlternateChunks()
document.Save("Result.docx", FormatType.Docx)
document.Close()
End Sub
UpdateDocumentFields()
Updates fields present in the document.
Declaration
public void UpdateDocumentFields()
Remarks
Updating of NUMPAGES field and Cross Reference field with Page number and Paragraph number options are not supported in Silverlight, WinRT, Universal and Windows Phone platforms.
Currently group shapes, drawing canvas, and table auto resizing are not supported in Word to PDF lay outing, and this may lead to update incorrect page number and total number of pages.
While updating NUMPAGES field and Cross Reference field with Page number and Paragraph number options uses makes use of our Word to PDF layouting engine which may lead to take some considerable amount of performance to update the above mentioned fields.
Examples
The following code example demonstrates how to update the fields present in Word document.
//Load an existing Word document into DocIO instance
WordDocument document = new WordDocument("Input.docx", FormatType.Docx);
//Updates the fields present in a document.
document.UpdateDocumentFields();
document.Save("Result.docx", FormatType.Docx);
document.Close();
'Load an existing Word document into DocIO instance
Dim document As New WordDocument("Input.docx", FormatType.Docx)
'Updates the fields present in a document.
document.UpdateDocumentFields()
document.Save("Result.docx", FormatType.Docx)
document.Close()
UpdateWordCount()
Updates Paragraphs count, Word count and Character count in the document.
Declaration
public void UpdateWordCount()
Examples
The following code example demonstrates how to update Paragraphs count, Word count and Character count in the document.
//Open an input word template
WordDocument document = new WordDocument(@"Template.docx", FormatType.Automatic);
//Update the Paragraphs count, Word count and Character count in the document
document.UpdateWordCount();
//Save and close the Word document instance.
document.Save("Output.docx", FormatType.Docx);
document.Close();
}
'Open an input word template
Dim document As New WordDocument("Template.docx", FormatType.Automatic)
'Update the Paragraphs count, Word count and Character count in the document.
document.UpdateWordCount()
'Save and close the Word document instance.
document.Save("Output.docx", FormatType.Docx)
document.Close()
WriteXmlAttributes(IXDLSAttributeWriter)
Writes object data as xml attributes.
Declaration
protected override void WriteXmlAttributes(IXDLSAttributeWriter writer)
Parameters
Type | Name | Description |
---|---|---|
IXDLSAttributeWriter | writer | The IXDLSAttributeWriter object. |
Overrides
WriteXmlContent(IXDLSContentWriter)
Writes object data as inside xml element.
Declaration
protected override void WriteXmlContent(IXDLSContentWriter writer)
Parameters
Type | Name | Description |
---|---|---|
IXDLSContentWriter | writer | The IXDLSContentWriter object. |