Class Document

Class Document

Namespace: Aspose.Words
Assembly: Aspose.Words.dll (25.12.0)

Represents a Word document.

To learn more, visit the Working with Document documentation article.

public class Document : DocumentBase, IEnumerable<Node>, IEnumerable, IXPathNavigable

Inheritance

object Node CompositeNode DocumentBase Document

Implements

IEnumerable<Node> , IEnumerable , IXPathNavigable

Inherited Members

object.GetType() , object.MemberwiseClone() , object.ToString() , object.Equals(object?) , object.Equals(object?, object?) , object.ReferenceEquals(object?, object?) , object.GetHashCode()

Examples

Shows how to execute a mail merge with data from a DataTable.

public void ExecuteDataTable()
                                                                        {
                                                                            DataTable table = new DataTable("Test");
                                                                            table.Columns.Add("CustomerName");
                                                                            table.Columns.Add("Address");
                                                                            table.Rows.Add(new object[] { "Thomas Hardy", "120 Hanover Sq., London" });
                                                                            table.Rows.Add(new object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

                                                                            // Below are two ways of using a DataTable as the data source for a mail merge.
                                                                            // 1 -  Use the entire table for the mail merge to create one output mail merge document for every row in the table:
                                                                            Document doc = CreateSourceDocExecuteDataTable();

                                                                            doc.MailMerge.Execute(table);

                                                                            doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.WholeTable.docx");

                                                                            // 2 -  Use one row of the table to create one output mail merge document:
                                                                            doc = CreateSourceDocExecuteDataTable();

                                                                            doc.MailMerge.Execute(table.Rows[1]);

                                                                            doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.OneRow.docx");
                                                                        }

                                                                        /// <summary>
                                                                        /// Creates a mail merge source document.
                                                                        /// </summary>
                                                                        private static Document CreateSourceDocExecuteDataTable()
                                                                        {
                                                                            Document doc = new Document();
                                                                            DocumentBuilder builder = new DocumentBuilder(doc);

                                                                            builder.InsertField(" MERGEFIELD CustomerName ");
                                                                            builder.InsertParagraph();
                                                                            builder.InsertField(" MERGEFIELD Address ");

                                                                            return doc;
                                                                        }

Remarks

The Aspose.Words.Document is a central object in the Aspose.Words library.

To load an existing document in any of the Aspose.Words.LoadFormat formats, pass a file name or a stream into one of the Aspose.Words.Document constructors. To create a blank document, call the constructor without parameters.

Use one of the Save method overloads to save the document in any of the Aspose.Words.SaveFormat formats.

To draw document pages directly onto a Graphics object use Aspose.Words.Document.RenderToScale(System.Int32,System.Drawing.Graphics,System.Single,System.Single,System.Single) or Aspose.Words.Document.RenderToSize(System.Int32,System.Drawing.Graphics,System.Single,System.Single,System.Single,System.Single) method.

To print the document, use one of the Aspose.Words.Document.Print(System.String) methods.

Aspose.Words.Document.MailMerge is the Aspose.Words's reporting engine that allows to populate reports designed in Microsoft Word with data from various data sources quickly and easily. The data can be from a DataSet, DataTable, DataView, IDataReader or an array of values. MailMerge will go through the records found in the data source and insert them into mail merge fields in the document growing it as necessary.

Aspose.Words.Document stores document-wide information such as Aspose.Words.DocumentBase.Styles, Aspose.Words.Document.BuiltInDocumentProperties, Aspose.Words.Document.CustomDocumentProperties, lists and macros. Most of these objects are accessible via the corresponding properties of the Aspose.Words.Document.

The Aspose.Words.Document is a root node of a tree that contains all other nodes of the document. The tree is a Composite design pattern and in many ways similar to XmlDocument. The content of the document can be manipulated freely programmatically:

  • The nodes of the document can be accessed via typed collections, for example Aspose.Words.Document.Sections, Aspose.Words.ParagraphCollection etc.
  • The nodes of the document can be selected by their node type using Aspose.Words.CompositeNode.GetChildNodes(Aspose.Words.NodeType,System.Boolean) or using an XPath query with Aspose.Words.CompositeNode.SelectNodes(System.String) or Aspose.Words.CompositeNode.SelectSingleNode(System.String).
  • Content nodes can be added or removed from anywhere in the document using Aspose.Words.CompositeNode.InsertBefore``1(``0,Aspose.Words.Node), Aspose.Words.CompositeNode.InsertAfter``1(``0,Aspose.Words.Node), Aspose.Words.CompositeNode.RemoveChild``1(``0) and other methods provided by the base class Aspose.Words.CompositeNode.
  • The formatting attributes of each node can be changed via the properties of that node.

Consider using Aspose.Words.DocumentBuilder that simplifies the task of programmatically creating or populating the document tree.

The Aspose.Words.Document can contain only Aspose.Words.Section objects.

In Microsoft Word, a valid document needs to have at least one section.

Constructors

Document()

Creates a blank Word document.

public Document()

Examples

Shows how to format a run of text using its font property.

Document doc = new Document();
                                                                     Run run = new Run(doc, "Hello world!");

                                                                     Aspose.Words.Font font = run.Font;
                                                                     font.Name = "Courier New";
                                                                     font.Size = 36;
                                                                     font.HighlightColor = Color.Yellow;

                                                                     doc.FirstSection.Body.FirstParagraph.AppendChild(run);
                                                                     doc.Save(ArtifactsDir + "Font.CreateFormattedRun.docx");

Shows how to create simple document.

Document doc = new Document();

                                               // New Document objects by default come with the minimal set of nodes
                                               // required to begin adding content such as text and shapes: a Section, a Body, and a Paragraph.
                                               doc.AppendChild(new Section(doc))
                                                   .AppendChild(new Body(doc))
                                                   .AppendChild(new Paragraph(doc))
                                                   .AppendChild(new Run(doc, "Hello world!"));

Shows how to create and load documents.

// There are two ways of creating a Document object using Aspose.Words.
                                                  // 1 -  Create a blank document:
                                                  Document doc = new Document();

                                                  // New Document objects by default come with the minimal set of nodes
                                                  // required to begin adding content such as text and shapes: a Section, a Body, and a Paragraph.
                                                  doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, "Hello world!"));

                                                  // 2 -  Load a document that exists in the local file system:
                                                  doc = new Document(MyDir + "Document.docx");

                                                  // Loaded documents will have contents that we can access and edit.
                                                  Assert.That(doc.FirstSection.Body.FirstParagraph.GetText().Trim(), Is.EqualTo("Hello World!"));

                                                  // Some operations that need to occur during loading, such as using a password to decrypt a document,
                                                  // can be done by passing a LoadOptions object when loading the document.
                                                  doc = new Document(MyDir + "Encrypted.docx", new LoadOptions("docPassword"));

                                                  Assert.That(doc.FirstSection.Body.FirstParagraph.GetText().Trim(), Is.EqualTo("Test encrypted document."));

Remarks

A blank document is retrieved from resources, and by default, the resulting document looks more like created by Aspose.Words.Settings.MsWordVersion.Word2007. This blank document contains a default fonts table, minimal default styles, and latent styles.

Aspose.Words.Settings.CompatibilityOptions.OptimizeFor(Aspose.Words.Settings.MsWordVersion) method can be used to optimize the document contents as well as default Aspose.Words behavior to a particular version of MS Word.

The document paper size is Letter by default. If you want to change page setup, use Aspose.Words.Section.PageSetup.

After creation, you can use Aspose.Words.DocumentBuilder to add document content easily.

Document(string)

Opens an existing document from a file. Automatically detects the file format.

public Document(string fileName)

Parameters

fileName string

File name of the document to open.

Examples

Shows how to open a document and convert it to .PDF.

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

                                                               doc.Save(ArtifactsDir + "Document.ConvertToPdf.pdf");

Shows how to convert a PDF to a .docx.

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

                                                 builder.Write("Hello world!");

                                                 doc.Save(ArtifactsDir + "PDF2Word.ConvertPdfToDocx.pdf");

                                                 // Load the PDF document that we just saved, and convert it to .docx.
                                                 Document pdfDoc = new Document(ArtifactsDir + "PDF2Word.ConvertPdfToDocx.pdf");

                                                 pdfDoc.Save(ArtifactsDir + "PDF2Word.ConvertPdfToDocx.docx");

Shows how to load a PDF.

Document doc = new Aspose.Words.Document();
                                   DocumentBuilder builder = new DocumentBuilder(doc);

                                   builder.Write("Hello world!");

                                   doc.Save(ArtifactsDir + "PDF2Word.LoadPdf.pdf");

                                   // Below are two ways of loading PDF documents using Aspose products.
                                   // 1 -  Load as an Aspose.Words document:
                                   Document asposeWordsDoc = new Document(ArtifactsDir + "PDF2Word.LoadPdf.pdf");

                                   Assert.That(asposeWordsDoc.GetText().Trim(), Is.EqualTo("Hello world!"));

                                   // 2 -  Load as an Aspose.Pdf document:
                                   Aspose.Pdf.Document asposePdfDoc = new Aspose.Pdf.Document(ArtifactsDir + "PDF2Word.LoadPdf.pdf");

                                   TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber();
                                   asposePdfDoc.Pages.Accept(textFragmentAbsorber);

                                   Assert.That(textFragmentAbsorber.Text.Trim(), Is.EqualTo("Hello world!"));

Exceptions

UnsupportedFileFormatException

The document format is not recognized or not supported.

FileCorruptedException

The document appears to be corrupted and cannot be loaded.

Exception

There is a problem with the document and it should be reported to Aspose.Words developers.

IOException

There is an input/output exception.

IncorrectPasswordException

The document is encrypted and requires a password to open, but you supplied an incorrect password.

ArgumentException

The name of the file cannot be null or empty string.

Document(string, LoadOptions)

Opens an existing document from a file. Allows to specify additional options such as an encryption password.

public Document(string fileName, LoadOptions loadOptions)

Parameters

fileName string

File name of the document to open.

loadOptions LoadOptions

Additional options to use when loading a document. Can be null.

Examples

Shows how to load an encrypted Microsoft Word document.

Document doc;

                                                                  // Aspose.Words throw an exception if we try to open an encrypted document without its password.
                                                                  Assert.Throws<IncorrectPasswordException>(() => doc = new Document(MyDir + "Encrypted.docx"));

                                                                  // When loading such a document, the password is passed to the document's constructor using a LoadOptions object.
                                                                  LoadOptions options = new LoadOptions("docPassword");

                                                                  // There are two ways of loading an encrypted document with a LoadOptions object.
                                                                  // 1 -  Load the document from the local file system by filename:
                                                                  doc = new Document(MyDir + "Encrypted.docx", options);
                                                                  // 2 -  Load the document from a stream:
                                                                  using (Stream stream = File.OpenRead(MyDir + "Encrypted.docx"))
                                                                  {
                                                                      doc = new Document(stream, options);
                                                                  }

Shows how to create and load documents.

// There are two ways of creating a Document object using Aspose.Words.
                                                  // 1 -  Create a blank document:
                                                  Document doc = new Document();

                                                  // New Document objects by default come with the minimal set of nodes
                                                  // required to begin adding content such as text and shapes: a Section, a Body, and a Paragraph.
                                                  doc.FirstSection.Body.FirstParagraph.AppendChild(new Run(doc, "Hello world!"));

                                                  // 2 -  Load a document that exists in the local file system:
                                                  doc = new Document(MyDir + "Document.docx");

                                                  // Loaded documents will have contents that we can access and edit.
                                                  Assert.That(doc.FirstSection.Body.FirstParagraph.GetText().Trim(), Is.EqualTo("Hello World!"));

                                                  // Some operations that need to occur during loading, such as using a password to decrypt a document,
                                                  // can be done by passing a LoadOptions object when loading the document.
                                                  doc = new Document(MyDir + "Encrypted.docx", new LoadOptions("docPassword"));

                                                  Assert.That(doc.FirstSection.Body.FirstParagraph.GetText().Trim(), Is.EqualTo("Test encrypted document."));

Exceptions

UnsupportedFileFormatException

The document format is not recognized or not supported.

FileCorruptedException

The document appears to be corrupted and cannot be loaded.

Exception

There is a problem with the document and it should be reported to Aspose.Words developers.

IOException

There is an input/output exception.

IncorrectPasswordException

The document is encrypted and requires a password to open, but you supplied an incorrect password.

ArgumentException

The name of the file cannot be null or empty string.

Document(Stream)

Opens an existing document from a stream. Automatically detects the file format.

public Document(Stream stream)

Parameters

stream Stream

Stream where to load the document from.

Examples

Shows how to load a document using a stream.

using (Stream stream = File.OpenRead(MyDir + "Document.docx"))
                                                       {
                                                           Document doc = new Document(stream);

                                                           Assert.That(doc.GetText().Trim(), Is.EqualTo("Hello World!\r\rHello Word!\r\r\rHello World!"));
                                                       }

Shows how to load a document from a URL.

// Create a URL that points to a Microsoft Word document.
                                                   const string url = "https://filesamples.com/samples/document/docx/sample3.docx";

                                                   // Download the document into a byte array, then load that array into a document using a memory stream.
                                                   using (HttpClient httpClient = new HttpClient())
                                                   {
                                                       HttpResponseMessage response = httpClient.GetAsync(url).Result;
                                                       byte[] dataBytes = response.Content.ReadAsByteArrayAsync().Result;

                                                       using (MemoryStream byteStream = new MemoryStream(dataBytes))
                                                       {
                                                           Document doc = new Document(byteStream);

                                                           // At this stage, we can read and edit the document's contents and then save it to the local file system.
                                                           Assert.That(doc.FirstSection.Body.Paragraphs[3].GetText().Trim(), Is.EqualTo("There are eight section headings in this document. At the beginning, \"Sample Document\" is a level 1 heading. " +
                                                                         "The main section headings, such as \"Headings\" and \"Lists\" are level 2 headings. " +
                                                                           "The Tables section contains two sub-headings, \"Simple Table\" and \"Complex Table,\" which are both level 3 headings."));

                                                           doc.Save(ArtifactsDir + "Document.LoadFromWeb.docx");
                                                       }
                                                   }

Remarks

The document must be stored at the beginning of the stream. The stream must support random positioning.

Exceptions

UnsupportedFileFormatException

The document format is not recognized or not supported.

FileCorruptedException

The document appears to be corrupted and cannot be loaded.

Exception

There is a problem with the document and it should be reported to Aspose.Words developers.

IOException

There is an input/output exception.

IncorrectPasswordException

The document is encrypted and requires a password to open, but you supplied an incorrect password.

ArgumentNullException

The stream cannot be null.

NotSupportedException

The stream does not support reading or seeking.

ObjectDisposedException

The stream is a disposed object.

Document(Stream, LoadOptions)

Opens an existing document from a stream. Allows to specify additional options such as an encryption password.

public Document(Stream stream, LoadOptions loadOptions)

Parameters

stream Stream

The stream where to load the document from.

loadOptions LoadOptions

Additional options to use when loading a document. Can be null.

Examples

Shows how to load an encrypted Microsoft Word document.

Document doc;

                                                                  // Aspose.Words throw an exception if we try to open an encrypted document without its password.
                                                                  Assert.Throws<IncorrectPasswordException>(() => doc = new Document(MyDir + "Encrypted.docx"));

                                                                  // When loading such a document, the password is passed to the document's constructor using a LoadOptions object.
                                                                  LoadOptions options = new LoadOptions("docPassword");

                                                                  // There are two ways of loading an encrypted document with a LoadOptions object.
                                                                  // 1 -  Load the document from the local file system by filename:
                                                                  doc = new Document(MyDir + "Encrypted.docx", options);
                                                                  // 2 -  Load the document from a stream:
                                                                  using (Stream stream = File.OpenRead(MyDir + "Encrypted.docx"))
                                                                  {
                                                                      doc = new Document(stream, options);
                                                                  }

Shows how to open an HTML document with images from a stream using a base URI.

using (Stream stream = File.OpenRead(MyDir + "Document.html"))
                                                                                         {
                                                                                             // Pass the URI of the base folder while loading it
                                                                                             // so that any images with relative URIs in the HTML document can be found.
                                                                                             LoadOptions loadOptions = new LoadOptions();
                                                                                             loadOptions.BaseUri = ImageDir;

                                                                                             Document doc = new Document(stream, loadOptions);

                                                                                             // Verify that the first shape of the document contains a valid image.
                                                                                             Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

                                                                                             Assert.That(shape.IsImage, Is.True);
                                                                                             Assert.That(shape.ImageData.ImageBytes, Is.Not.Null);
                                                                                             Assert.That(ConvertUtil.PointToPixel(shape.Width), Is.EqualTo(32.0).Within(0.01));
                                                                                             Assert.That(ConvertUtil.PointToPixel(shape.Height), Is.EqualTo(32.0).Within(0.01));
                                                                                         }

Shows how save a web page as a .docx file.

const string url = "https://products.aspose.com/words/";

                                                     using (HttpClient client = new HttpClient())
                                                     {
                                                         byte[] bytes = client.GetByteArrayAsync(url).GetAwaiter().GetResult();

                                                         using (MemoryStream stream = new MemoryStream(bytes))
                                                         {
                                                             // The URL is used again as a baseUri to ensure that any relative image paths are retrieved correctly.
                                                             LoadOptions options = new LoadOptions(LoadFormat.Html, "", url);

                                                             // Load the HTML document from stream and pass the LoadOptions object.
                                                             Document doc = new Document(stream, options);

                                                             // At this stage, we can read and edit the document's contents and then save it to the local file system.
                                                             doc.Save(ArtifactsDir + "Document.InsertHtmlFromWebPage.docx");
                                                         }
                                                     }

Remarks

The document must be stored at the beginning of the stream. The stream must support random positioning.

Exceptions

UnsupportedFileFormatException

The document format is not recognized or not supported.

FileCorruptedException

The document appears to be corrupted and cannot be loaded.

Exception

There is a problem with the document and it should be reported to Aspose.Words developers.

IOException

There is an input/output exception.

IncorrectPasswordException

The document is encrypted and requires a password to open, but you supplied an incorrect password.

ArgumentNullException

The stream cannot be null.

NotSupportedException

The stream does not support reading or seeking.

ObjectDisposedException

The stream is a disposed object.

Properties

AttachedTemplate

Gets or sets the full path of the template attached to the document.

public string AttachedTemplate { get; set; }

Property Value

string

Examples

Shows how to set a default template for documents that do not have attached templates.

Document doc = new Document();

                                                                                                 // Enable automatic style updating, but do not attach a template document.
                                                                                                 doc.AutomaticallyUpdateStyles = true;

                                                                                                 Assert.That(doc.AttachedTemplate, Is.EqualTo(string.Empty));

                                                                                                 // Since there is no template document, the document had nowhere to track style changes.
                                                                                                 // Use a SaveOptions object to automatically set a template
                                                                                                 // if a document that we are saving does not have one.
                                                                                                 SaveOptions options = SaveOptions.CreateSaveOptions("Document.DefaultTemplate.docx");
                                                                                                 options.DefaultTemplate = MyDir + "Business brochure.dotx";

                                                                                                 doc.Save(ArtifactsDir + "Document.DefaultTemplate.docx", options);

Remarks

Empty string means the document is attached to the Normal template.

Aspose.Words.Properties.BuiltInDocumentProperties.Template

Exceptions

ArgumentNullException

Throws if you attempt to set to a null value.

AutomaticallyUpdateStyles

Gets or sets a flag indicating whether the styles in the document are updated to match the styles in the attached template each time the document is opened in MS Word.

public bool AutomaticallyUpdateStyles { get; set; }

Property Value

bool

Examples

Shows how to attach a template to a document.

Document doc = new Document();

                                                        // Microsoft Word documents by default come with an attached template called "Normal.dotm".
                                                        // There is no default template for blank Aspose.Words documents.
                                                        Assert.That(doc.AttachedTemplate, Is.EqualTo(string.Empty));

                                                        // Attach a template, then set the flag to apply style changes
                                                        // within the template to styles in our document.
                                                        doc.AttachedTemplate = MyDir + "Business brochure.dotx";
                                                        doc.AutomaticallyUpdateStyles = true;

                                                        doc.Save(ArtifactsDir + "Document.AutomaticallyUpdateStyles.docx");

Shows how to set a default template for documents that do not have attached templates.

Document doc = new Document();

                                                                                                 // Enable automatic style updating, but do not attach a template document.
                                                                                                 doc.AutomaticallyUpdateStyles = true;

                                                                                                 Assert.That(doc.AttachedTemplate, Is.EqualTo(string.Empty));

                                                                                                 // Since there is no template document, the document had nowhere to track style changes.
                                                                                                 // Use a SaveOptions object to automatically set a template
                                                                                                 // if a document that we are saving does not have one.
                                                                                                 SaveOptions options = SaveOptions.CreateSaveOptions("Document.DefaultTemplate.docx");
                                                                                                 options.DefaultTemplate = MyDir + "Business brochure.dotx";

                                                                                                 doc.Save(ArtifactsDir + "Document.DefaultTemplate.docx", options);

Bibliography

Gets the Aspose.Words.Document.Bibliography object that represents the list of sources available in the document.

public Bibliography Bibliography { get; }

Property Value

Bibliography

Examples

Shows how to get bibliography sources available in the document.

Document document = new Document(MyDir + "Bibliography sources.docx");

                                                                           Bibliography bibliography = document.Bibliography;
                                                                           Assert.That(bibliography.Sources.Count, Is.EqualTo(12));

                                                                           // Get default data from bibliography sources.
                                                                           Source source = bibliography.Sources.FirstOrDefault();
                                                                           Assert.That(source.Title, Is.EqualTo("Book 0 (No LCID)"));
                                                                           Assert.That(source.SourceType, Is.EqualTo(SourceType.Book));
                                                                           Assert.That(source.Contributors.Count(), Is.EqualTo(3));
                                                                           Assert.That(source.AbbreviatedCaseNumber, Is.Null);
                                                                           Assert.That(source.AlbumTitle, Is.Null);
                                                                           Assert.That(source.BookTitle, Is.Null);
                                                                           Assert.That(source.Broadcaster, Is.Null);
                                                                           Assert.That(source.BroadcastTitle, Is.Null);
                                                                           Assert.That(source.CaseNumber, Is.Null);
                                                                           Assert.That(source.ChapterNumber, Is.Null);
                                                                           Assert.That(source.Comments, Is.Null);
                                                                           Assert.That(source.ConferenceName, Is.Null);
                                                                           Assert.That(source.CountryOrRegion, Is.Null);
                                                                           Assert.That(source.Court, Is.Null);
                                                                           Assert.That(source.Day, Is.Null);
                                                                           Assert.That(source.DayAccessed, Is.Null);
                                                                           Assert.That(source.Department, Is.Null);
                                                                           Assert.That(source.Distributor, Is.Null);
                                                                           Assert.That(source.Doi, Is.Null);
                                                                           Assert.That(source.Edition, Is.Null);
                                                                           Assert.That(source.Guid, Is.Null);
                                                                           Assert.That(source.Institution, Is.Null);
                                                                           Assert.That(source.InternetSiteTitle, Is.Null);
                                                                           Assert.That(source.Issue, Is.Null);
                                                                           Assert.That(source.JournalName, Is.Null);
                                                                           Assert.That(source.Lcid, Is.Null);
                                                                           Assert.That(source.Medium, Is.Null);
                                                                           Assert.That(source.Month, Is.Null);
                                                                           Assert.That(source.MonthAccessed, Is.Null);
                                                                           Assert.That(source.NumberVolumes, Is.Null);
                                                                           Assert.That(source.Pages, Is.Null);
                                                                           Assert.That(source.PatentNumber, Is.Null);
                                                                           Assert.That(source.PeriodicalTitle, Is.Null);
                                                                           Assert.That(source.ProductionCompany, Is.Null);
                                                                           Assert.That(source.PublicationTitle, Is.Null);
                                                                           Assert.That(source.Publisher, Is.Null);
                                                                           Assert.That(source.RecordingNumber, Is.Null);
                                                                           Assert.That(source.RefOrder, Is.Null);
                                                                           Assert.That(source.Reporter, Is.Null);
                                                                           Assert.That(source.ShortTitle, Is.Null);
                                                                           Assert.That(source.StandardNumber, Is.Null);
                                                                           Assert.That(source.StateOrProvince, Is.Null);
                                                                           Assert.That(source.Station, Is.Null);
                                                                           Assert.That(source.Tag, Is.EqualTo("BookNoLCID"));
                                                                           Assert.That(source.Theater, Is.Null);
                                                                           Assert.That(source.ThesisType, Is.Null);
                                                                           Assert.That(source.Type, Is.Null);
                                                                           Assert.That(source.Url, Is.Null);
                                                                           Assert.That(source.Version, Is.Null);
                                                                           Assert.That(source.Volume, Is.Null);
                                                                           Assert.That(source.Year, Is.Null);
                                                                           Assert.That(source.YearAccessed, Is.Null);

                                                                           // Also, you can create a new source.
                                                                           Source newSource = new Source("New source", SourceType.Misc);

                                                                           ContributorCollection contributors = source.Contributors;
                                                                           Assert.That(contributors.Artist, Is.Null);
                                                                           Assert.That(contributors.BookAuthor, Is.Null);
                                                                           Assert.That(contributors.Compiler, Is.Null);
                                                                           Assert.That(contributors.Composer, Is.Null);
                                                                           Assert.That(contributors.Conductor, Is.Null);
                                                                           Assert.That(contributors.Counsel, Is.Null);
                                                                           Assert.That(contributors.Director, Is.Null);
                                                                           Assert.That(contributors.Editor, Is.Not.Null);
                                                                           Assert.That(contributors.Interviewee, Is.Null);
                                                                           Assert.That(contributors.Interviewer, Is.Null);
                                                                           Assert.That(contributors.Inventor, Is.Null);
                                                                           Assert.That(contributors.Performer, Is.Null);
                                                                           Assert.That(contributors.Producer, Is.Null);
                                                                           Assert.That(contributors.Translator, Is.Not.Null);
                                                                           Assert.That(contributors.Writer, Is.Null);

                                                                           Contributor editor  = contributors.Editor;
                                                                           Assert.That(((PersonCollection)editor).Count(), Is.EqualTo(2));

                                                                           PersonCollection authors = (PersonCollection)contributors.Author;
                                                                           Assert.That(authors.Count(), Is.EqualTo(2));

                                                                           Person person = authors[0];
                                                                           Assert.That(person.First, Is.EqualTo("Roxanne"));
                                                                           Assert.That(person.Middle, Is.EqualTo("Brielle"));
                                                                           Assert.That(person.Last, Is.EqualTo("Tejeda"));

BuiltInDocumentProperties

Returns a collection that represents all the built-in document properties of the document.

public BuiltInDocumentProperties BuiltInDocumentProperties { get; }

Property Value

BuiltInDocumentProperties

Examples

Shows how to work with built-in document properties.

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

                                                               // The "Document" object contains some of its metadata in its members.
                                                               Console.WriteLine($"Document filename:\n\t \"{doc.OriginalFileName}\"");

                                                               // The document also stores metadata in its built-in properties.
                                                               // Each built-in property is a member of the document's "BuiltInDocumentProperties" object.
                                                               Console.WriteLine("Built-in Properties:");
                                                               foreach (DocumentProperty docProperty in doc.BuiltInDocumentProperties)
                                                               {
                                                                   Console.WriteLine(docProperty.Name);
                                                                   Console.WriteLine($"\tType:\t{docProperty.Type}");

                                                                   // Some properties may store multiple values.
                                                                   if (docProperty.Value is ICollection<object>)
                                                                   {
                                                                       foreach (object value in docProperty.Value as ICollection<object>)
                                                                           Console.WriteLine($"\tValue:\t\"{value}\"");
                                                                   }
                                                                   else
                                                                   {
                                                                       Console.WriteLine($"\tValue:\t\"{docProperty.Value}\"");
                                                                   }
                                                               }

CompatibilityOptions

Provides access to document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).

public CompatibilityOptions CompatibilityOptions { get; }

Property Value

CompatibilityOptions

Examples

Shows how to optimize the document for different versions of Microsoft Word.

public void OptimizeFor()
                                                                                       {
                                                                                           Document doc = new Document();

                                                                                           // This object contains an extensive list of flags unique to each document
                                                                                           // that allow us to facilitate backward compatibility with older versions of Microsoft Word.
                                                                                           CompatibilityOptions options = doc.CompatibilityOptions;

                                                                                           // Print the default settings for a blank document.
                                                                                           Console.WriteLine("\nDefault optimization settings:");
                                                                                           PrintCompatibilityOptions(options);

                                                                                           // We can access these settings in Microsoft Word via "File" -> "Options" -> "Advanced" -> "Compatibility options for...".
                                                                                           doc.Save(ArtifactsDir + "CompatibilityOptions.OptimizeFor.DefaultSettings.docx");

                                                                                           // We can use the OptimizeFor method to ensure optimal compatibility with a specific Microsoft Word version.
                                                                                           doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2010);
                                                                                           Console.WriteLine("\nOptimized for Word 2010:");
                                                                                           PrintCompatibilityOptions(options);

                                                                                           doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2000);
                                                                                           Console.WriteLine("\nOptimized for Word 2000:");
                                                                                           PrintCompatibilityOptions(options);
                                                                                       }

                                                                                       /// <summary>
                                                                                       /// Groups all flags in a document's compatibility options object by state, then prints each group.
                                                                                       /// </summary>
                                                                                       private static void PrintCompatibilityOptions(CompatibilityOptions options)
                                                                                       {
                                                                                           IList<string> enabledOptions = new List<string>();
                                                                                           IList<string> disabledOptions = new List<string>();
                                                                                           AddOptionName(options.AdjustLineHeightInTable, "AdjustLineHeightInTable", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.AlignTablesRowByRow, "AlignTablesRowByRow", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.AllowSpaceOfSameStyleInTable, "AllowSpaceOfSameStyleInTable", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.ApplyBreakingRules, "ApplyBreakingRules", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.AutoSpaceLikeWord95, "AutoSpaceLikeWord95", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.AutofitToFirstFixedWidthCell, "AutofitToFirstFixedWidthCell", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.BalanceSingleByteDoubleByteWidth, "BalanceSingleByteDoubleByteWidth", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.CachedColBalance, "CachedColBalance", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.ConvMailMergeEsc, "ConvMailMergeEsc", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DisableOpenTypeFontFormattingFeatures, "DisableOpenTypeFontFormattingFeatures", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DisplayHangulFixedWidth, "DisplayHangulFixedWidth", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotAutofitConstrainedTables, "DoNotAutofitConstrainedTables", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotBreakConstrainedForcedTable, "DoNotBreakConstrainedForcedTable", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotBreakWrappedTables, "DoNotBreakWrappedTables", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotExpandShiftReturn, "DoNotExpandShiftReturn", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotLeaveBackslashAlone, "DoNotLeaveBackslashAlone", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotSnapToGridInCell, "DoNotSnapToGridInCell", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotSuppressIndentation, "DoNotSnapToGridInCell", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotSuppressParagraphBorders, "DoNotSuppressParagraphBorders", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotUseEastAsianBreakRules, "DoNotUseEastAsianBreakRules", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotUseHTMLParagraphAutoSpacing, "DoNotUseHTMLParagraphAutoSpacing", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotUseIndentAsNumberingTabStop, "DoNotUseIndentAsNumberingTabStop", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotVertAlignCellWithSp, "DoNotVertAlignCellWithSp", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotVertAlignInTxbx, "DoNotVertAlignInTxbx", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.DoNotWrapTextWithPunct, "DoNotWrapTextWithPunct", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.FootnoteLayoutLikeWW8, "FootnoteLayoutLikeWW8", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.ForgetLastTabAlignment, "ForgetLastTabAlignment", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.GrowAutofit, "GrowAutofit", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.LayoutRawTableWidth, "LayoutRawTableWidth", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.LayoutTableRowsApart, "LayoutTableRowsApart", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.LineWrapLikeWord6, "LineWrapLikeWord6", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.MWSmallCaps, "MWSmallCaps", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.NoColumnBalance, "NoColumnBalance", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.NoExtraLineSpacing, "NoExtraLineSpacing", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.NoLeading, "NoLeading", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.NoSpaceRaiseLower, "NoSpaceRaiseLower", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.NoTabHangInd, "NoTabHangInd", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.OverrideTableStyleFontSizeAndJustification, "OverrideTableStyleFontSizeAndJustification", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.PrintBodyTextBeforeHeader, "PrintBodyTextBeforeHeader", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.PrintColBlack, "PrintColBlack", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SelectFldWithFirstOrLastChar, "SelectFldWithFirstOrLastChar", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.ShapeLayoutLikeWW8, "ShapeLayoutLikeWW8", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.ShowBreaksInFrames, "ShowBreaksInFrames", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SpaceForUL, "SpaceForUL", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SpacingInWholePoints, "SpacingInWholePoints", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SplitPgBreakAndParaMark, "SplitPgBreakAndParaMark", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SubFontBySize, "SubFontBySize", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SuppressBottomSpacing, "SuppressBottomSpacing", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SuppressSpBfAfterPgBrk, "SuppressSpBfAfterPgBrk", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SuppressSpacingAtTopOfPage, "SuppressSpacingAtTopOfPage", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SuppressTopSpacing, "SuppressTopSpacing", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SuppressTopSpacingWP, "SuppressTopSpacingWP", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SwapBordersFacingPgs, "SwapBordersFacingPgs", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning, "SwapInsideAndOutsideForMirrorIndentsAndRelativePositioning", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.TransparentMetafiles, "TransparentMetafiles", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.TruncateFontHeightsLikeWP6, "TruncateFontHeightsLikeWP6", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UICompat97To2003, "UICompat97To2003", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UlTrailSpace, "UlTrailSpace", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UnderlineTabInNumList, "UnderlineTabInNumList", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UseAltKinsokuLineBreakRules, "UseAltKinsokuLineBreakRules", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UseAnsiKerningPairs, "UseAnsiKerningPairs", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UseFELayout, "UseFELayout", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UseNormalStyleForList, "UseNormalStyleForList", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UsePrinterMetrics, "UsePrinterMetrics", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UseSingleBorderforContiguousCells, "UseSingleBorderforContiguousCells", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UseWord2002TableStyleRules, "UseWord2002TableStyleRules", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UseWord2010TableStyleRules, "UseWord2010TableStyleRules", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.UseWord97LineBreakRules, "UseWord97LineBreakRules", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.WPJustification, "WPJustification", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.WPSpaceWidth, "WPSpaceWidth", enabledOptions, disabledOptions);
                                                                                           AddOptionName(options.WrapTrailSpaces, "WrapTrailSpaces", enabledOptions, disabledOptions);
                                                                                           Console.WriteLine("\tEnabled options:");
                                                                                           foreach (string optionName in enabledOptions)
                                                                                               Console.WriteLine($"\t\t{optionName}");
                                                                                           Console.WriteLine("\tDisabled options:");
                                                                                           foreach (string optionName in disabledOptions)
                                                                                               Console.WriteLine($"\t\t{optionName}");
                                                                                       }

                                                                                       private static void AddOptionName(Boolean option, String optionName, IList<string> enabledOptions, IList<string> disabledOptions)
                                                                                       {
                                                                                           if (option)
                                                                                               enabledOptions.Add(optionName);
                                                                                           else
                                                                                               disabledOptions.Add(optionName);
                                                                                       }

Compliance

Gets the OOXML compliance version determined from the loaded document content. Makes sense only for OOXML documents.

public OoxmlCompliance Compliance { get; }

Property Value

OoxmlCompliance

Examples

Shows how to read a loaded document’s Open Office XML compliance version.

// The compliance version varies between documents created by different versions of Microsoft Word.
                                                                                    Document doc = new Document(MyDir + "Document.doc");
                                                                                    Assert.That(OoxmlCompliance.Ecma376_2006, Is.EqualTo(doc.Compliance));

                                                                                    doc = new Document(MyDir + "Document.docx");
                                                                                    Assert.That(OoxmlCompliance.Iso29500_2008_Transitional, Is.EqualTo(doc.Compliance));

Remarks

If you created a new blank document or load non OOXML document returns the Aspose.Words.Saving.OoxmlCompliance.Ecma376_2006 value.

CustomDocumentProperties

Returns a collection that represents all the custom document properties of the document.

public CustomDocumentProperties CustomDocumentProperties { get; }

Property Value

CustomDocumentProperties

Examples

Shows how to work with built-in document properties.

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

                                                               // The "Document" object contains some of its metadata in its members.
                                                               Console.WriteLine($"Document filename:\n\t \"{doc.OriginalFileName}\"");

                                                               // The document also stores metadata in its built-in properties.
                                                               // Each built-in property is a member of the document's "BuiltInDocumentProperties" object.
                                                               Console.WriteLine("Built-in Properties:");
                                                               foreach (DocumentProperty docProperty in doc.BuiltInDocumentProperties)
                                                               {
                                                                   Console.WriteLine(docProperty.Name);
                                                                   Console.WriteLine($"\tType:\t{docProperty.Type}");

                                                                   // Some properties may store multiple values.
                                                                   if (docProperty.Value is ICollection<object>)
                                                                   {
                                                                       foreach (object value in docProperty.Value as ICollection<object>)
                                                                           Console.WriteLine($"\tValue:\t\"{value}\"");
                                                                   }
                                                                   else
                                                                   {
                                                                       Console.WriteLine($"\tValue:\t\"{docProperty.Value}\"");
                                                                   }
                                                               }

CustomXmlParts

Gets or sets the collection of Custom XML Data Storage Parts.

public CustomXmlPartCollection CustomXmlParts { get; set; }

Property Value

CustomXmlPartCollection

Examples

Shows how to create a structured document tag with custom XML data.

Document doc = new Document();

                                                                              // Construct an XML part that contains data and add it to the document's collection.
                                                                              // If we enable the "Developer" tab in Microsoft Word,
                                                                              // we can find elements from this collection in the "XML Mapping Pane", along with a few default elements.
                                                                              string xmlPartId = Guid.NewGuid().ToString("B");
                                                                              string xmlPartContent = "<root><text>Hello world!</text></root>";
                                                                              CustomXmlPart xmlPart = doc.CustomXmlParts.Add(xmlPartId, xmlPartContent);

                                                                              Assert.That(xmlPart.Data, Is.EqualTo(Encoding.ASCII.GetBytes(xmlPartContent)));
                                                                              Assert.That(xmlPart.Id, Is.EqualTo(xmlPartId));

                                                                              // Below are two ways to refer to XML parts.
                                                                              // 1 -  By an index in the custom XML part collection:
                                                                              Assert.That(doc.CustomXmlParts[0], Is.EqualTo(xmlPart));

                                                                              // 2 -  By GUID:
                                                                              Assert.That(doc.CustomXmlParts.GetById(xmlPartId), Is.EqualTo(xmlPart));

                                                                              // Add an XML schema association.
                                                                              xmlPart.Schemas.Add("http://www.w3.org/2001/XMLSchema");

                                                                              // Clone a part, and then insert it into the collection.
                                                                              CustomXmlPart xmlPartClone = xmlPart.Clone();
                                                                              xmlPartClone.Id = Guid.NewGuid().ToString("B");
                                                                              doc.CustomXmlParts.Add(xmlPartClone);

                                                                              Assert.That(doc.CustomXmlParts.Count, Is.EqualTo(2));

                                                                              // Iterate through the collection and print the contents of each part.
                                                                              using (IEnumerator<CustomXmlPart> enumerator = doc.CustomXmlParts.GetEnumerator())
                                                                              {
                                                                                  int index = 0;
                                                                                  while (enumerator.MoveNext())
                                                                                  {
                                                                                      Console.WriteLine($"XML part index {index}, ID: {enumerator.Current.Id}");
                                                                                      Console.WriteLine($"\tContent: {Encoding.UTF8.GetString(enumerator.Current.Data)}");
                                                                                      index++;
                                                                                  }
                                                                              }

                                                                              // Use the "RemoveAt" method to remove the cloned part by index.
                                                                              doc.CustomXmlParts.RemoveAt(1);

                                                                              Assert.That(doc.CustomXmlParts.Count, Is.EqualTo(1));

                                                                              // Clone the XML parts collection, and then use the "Clear" method to remove all its elements at once.
                                                                              CustomXmlPartCollection customXmlParts = doc.CustomXmlParts.Clone();
                                                                              customXmlParts.Clear();

                                                                              // Create a structured document tag that will display our part's contents and insert it into the document body.
                                                                              StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Block);
                                                                              tag.XmlMapping.SetMapping(xmlPart, "/root[1]/text[1]", string.Empty);

                                                                              doc.FirstSection.Body.AppendChild(tag);

                                                                              doc.Save(ArtifactsDir + "StructuredDocumentTag.CustomXml.docx");

Remarks

Aspose.Words loads and saves Custom XML Parts into OOXML and DOC documents only.

This property cannot be null.

Aspose.Words.Markup.CustomXmlPart

DefaultTabStop

Gets or sets the interval (in points) between the default tab stops.

public double DefaultTabStop { get; set; }

Property Value

double

Examples

Shows how to set a custom interval for tab stop positions.

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

                                                                     // Set tab stops to appear every 72 points (1 inch).
                                                                     builder.Document.DefaultTabStop = 72;

                                                                     // Each tab character snaps the text after it to the next closest tab stop position.
                                                                     builder.Writeln("Hello" + ControlChar.Tab + "World!");
                                                                     builder.Writeln("Hello" + ControlChar.TabChar + "World!");

See Also

TabStopCollection , TabStop

DigitalSignatures

Gets the collection of digital signatures for this document and their validation results.

public DigitalSignatureCollection DigitalSignatures { get; }

Property Value

DigitalSignatureCollection

Examples

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

Document doc = new Document(MyDir + "Digitally signed.docx");

                                                                                            foreach (DigitalSignature signature in doc.DigitalSignatures)
                                                                                            {
                                                                                                Console.WriteLine($"{(signature.IsValid ? "Valid" : "Invalid")} signature: ");
                                                                                                Console.WriteLine($"\tReason:\t{signature.Comments}");
                                                                                                Console.WriteLine($"\tType:\t{signature.SignatureType}");
                                                                                                Console.WriteLine($"\tSign time:\t{signature.SignTime}");
                                                                                                Console.WriteLine($"\tSubject name:\t{signature.CertificateHolder.Certificate.SubjectName}");
                                                                                                Console.WriteLine($"\tIssuer name:\t{signature.CertificateHolder.Certificate.IssuerName.Name}");
                                                                                                Console.WriteLine();
                                                                                            }

Shows how to sign documents with X.509 certificates.

// Verify that a document is not signed.
                                                               Assert.That(FileFormatUtil.DetectFileFormat(MyDir + "Document.docx").HasDigitalSignature, Is.False);

                                                               // Create a CertificateHolder object from a PKCS12 file, which we will use to sign the document.
                                                               CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw", null);

                                                               // There are two ways of saving a signed copy of a document to the local file system:
                                                               // 1 - Designate a document by a local system filename and save a signed copy at a location specified by another filename.
                                                               SignOptions signOptions = new SignOptions { SignTime = DateTime.Now };
                                                               DigitalSignatureUtil.Sign(MyDir + "Document.docx", ArtifactsDir + "Document.DigitalSignature.docx",
                                                                   certificateHolder, signOptions);

                                                               Assert.That(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.DigitalSignature.docx").HasDigitalSignature, Is.True);

                                                               // 2 - Take a document from a stream and save a signed copy to another stream.
                                                               using (FileStream inDoc = new FileStream(MyDir + "Document.docx", FileMode.Open))
                                                               {
                                                                   using (FileStream outDoc = new FileStream(ArtifactsDir + "Document.DigitalSignature.docx", FileMode.Create))
                                                                   {
                                                                       DigitalSignatureUtil.Sign(inDoc, outDoc, certificateHolder);
                                                                   }
                                                               }

                                                               Assert.That(FileFormatUtil.DetectFileFormat(ArtifactsDir + "Document.DigitalSignature.docx").HasDigitalSignature, Is.True);

                                                               // Please verify that all of the document's digital signatures are valid and check their details.
                                                               Document signedDoc = new Document(ArtifactsDir + "Document.DigitalSignature.docx");
                                                               DigitalSignatureCollection digitalSignatureCollection = signedDoc.DigitalSignatures;

                                                               Assert.That(digitalSignatureCollection.IsValid, Is.True);
                                                               Assert.That(digitalSignatureCollection.Count, Is.EqualTo(1));
                                                               Assert.That(digitalSignatureCollection[0].SignatureType, Is.EqualTo(DigitalSignatureType.XmlDsig));
                                                               Assert.That(signedDoc.DigitalSignatures[0].IssuerName, Is.EqualTo("CN=Morzal.Me"));
                                                               Assert.That(signedDoc.DigitalSignatures[0].SubjectName, Is.EqualTo("CN=Morzal.Me"));

Remarks

This collection contains digital signatures that were loaded from the original document. These digital signatures will not be saved when you save this Aspose.Words.Document object into a file or stream because saving or converting will produce a document that is different from the original and the original digital signatures will no longer be valid.

This collection is never null. If the document is not signed, it will contain zero elements.

EndnoteOptions

Provides options that control numbering and positioning of endnotes in this document.

public EndnoteOptions EndnoteOptions { get; }

Property Value

EndnoteOptions

Examples

Shows how to select a different place where the document collects and displays its endnotes.

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

                                                                                                       // An endnote is a way to attach a reference or a side comment to text
                                                                                                       // that does not interfere with the main body text's flow. 
                                                                                                       // Inserting an endnote adds a small superscript reference symbol
                                                                                                       // at the main body text where we insert the endnote.
                                                                                                       // Each endnote also creates an entry at the end of the document, consisting of a symbol
                                                                                                       // that matches the reference symbol in the main body text.
                                                                                                       // The reference text that we pass to the document builder's "InsertEndnote" method.
                                                                                                       builder.Write("Hello world!");
                                                                                                       builder.InsertFootnote(FootnoteType.Endnote, "Endnote contents.");
                                                                                                       builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                                                                       builder.Write("This is the second section.");

                                                                                                       // We can use the "Position" property to determine where the document will place all its endnotes.
                                                                                                       // If we set the value of the "Position" property to "EndnotePosition.EndOfDocument",
                                                                                                       // every footnote will show up in a collection at the end of the document. This is the default value.
                                                                                                       // If we set the value of the "Position" property to "EndnotePosition.EndOfSection",
                                                                                                       // every footnote will show up in a collection at the end of the section whose text contains the endnote's reference mark.
                                                                                                       doc.EndnoteOptions.Position = endnotePosition;

                                                                                                       doc.Save(ArtifactsDir + "InlineStory.PositionEndnote.docx");

Shows how to set a number at which the document begins the footnote/endnote count.

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

                                                                                             // Footnotes and endnotes are a way to attach a reference or a side comment to text
                                                                                             // that does not interfere with the main body text's flow. 
                                                                                             // Inserting a footnote/endnote adds a small superscript reference symbol
                                                                                             // at the main body text where we insert the footnote/endnote.
                                                                                             // Each footnote/endnote also creates an entry, which consists of a symbol
                                                                                             // that matches the reference symbol in the main body text.
                                                                                             // The reference text that we pass to the document builder's "InsertEndnote" method.
                                                                                             // Footnote entries, by default, show up at the bottom of each page that contains
                                                                                             // their reference symbols, and endnotes show up at the end of the document.
                                                                                             builder.Write("Text 1. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 1.");
                                                                                             builder.Write("Text 2. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 2.");
                                                                                             builder.Write("Text 3. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 3.");

                                                                                             builder.InsertParagraph();

                                                                                             builder.Write("Text 1. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 1.");
                                                                                             builder.Write("Text 2. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 2.");
                                                                                             builder.Write("Text 3. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 3.");

                                                                                             // By default, the reference symbol for each footnote and endnote is its index
                                                                                             // among all the document's footnotes/endnotes. Each document maintains separate counts
                                                                                             // for footnotes and for endnotes, which both begin at 1.
                                                                                             Assert.That(doc.FootnoteOptions.StartNumber, Is.EqualTo(1));
                                                                                             Assert.That(doc.EndnoteOptions.StartNumber, Is.EqualTo(1));

                                                                                             // We can use the "StartNumber" property to get the document to
                                                                                             // begin a footnote or endnote count at a different number.
                                                                                             doc.EndnoteOptions.NumberStyle = NumberStyle.Arabic;
                                                                                             doc.EndnoteOptions.StartNumber = 50;

                                                                                             doc.Save(ArtifactsDir + "InlineStory.StartNumber.docx");

Shows how to change the number style of footnote/endnote reference marks.

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

                                                                                    // Footnotes and endnotes are a way to attach a reference or a side comment to text
                                                                                    // that does not interfere with the main body text's flow. 
                                                                                    // Inserting a footnote/endnote adds a small superscript reference symbol
                                                                                    // at the main body text where we insert the footnote/endnote.
                                                                                    // Each footnote/endnote also creates an entry, which consists of a symbol that matches the reference
                                                                                    // symbol in the main body text. The reference text that we pass to the document builder's "InsertEndnote" method.
                                                                                    // Footnote entries, by default, show up at the bottom of each page that contains
                                                                                    // their reference symbols, and endnotes show up at the end of the document.
                                                                                    builder.Write("Text 1. ");
                                                                                    builder.InsertFootnote(FootnoteType.Footnote, "Footnote 1.");
                                                                                    builder.Write("Text 2. ");
                                                                                    builder.InsertFootnote(FootnoteType.Footnote, "Footnote 2.");
                                                                                    builder.Write("Text 3. ");
                                                                                    builder.InsertFootnote(FootnoteType.Footnote, "Footnote 3.", "Custom footnote reference mark");

                                                                                    builder.InsertParagraph();

                                                                                    builder.Write("Text 1. ");
                                                                                    builder.InsertFootnote(FootnoteType.Endnote, "Endnote 1.");
                                                                                    builder.Write("Text 2. ");
                                                                                    builder.InsertFootnote(FootnoteType.Endnote, "Endnote 2.");
                                                                                    builder.Write("Text 3. ");
                                                                                    builder.InsertFootnote(FootnoteType.Endnote, "Endnote 3.", "Custom endnote reference mark");

                                                                                    // By default, the reference symbol for each footnote and endnote is its index
                                                                                    // among all the document's footnotes/endnotes. Each document maintains separate counts
                                                                                    // for footnotes and for endnotes. By default, footnotes display their numbers using Arabic numerals,
                                                                                    // and endnotes display their numbers in lowercase Roman numerals.
                                                                                    Assert.That(doc.FootnoteOptions.NumberStyle, Is.EqualTo(NumberStyle.Arabic));
                                                                                    Assert.That(doc.EndnoteOptions.NumberStyle, Is.EqualTo(NumberStyle.LowercaseRoman));

                                                                                    // We can use the "NumberStyle" property to apply custom numbering styles to footnotes and endnotes.
                                                                                    // This will not affect footnotes/endnotes with custom reference marks.
                                                                                    doc.FootnoteOptions.NumberStyle = NumberStyle.UppercaseRoman;
                                                                                    doc.EndnoteOptions.NumberStyle = NumberStyle.UppercaseLetter;

                                                                                    doc.Save(ArtifactsDir + "InlineStory.RefMarkNumberStyle.docx");

Shows how to restart footnote/endnote numbering at certain places in the document.

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

                                                                                             // Footnotes and endnotes are a way to attach a reference or a side comment to text
                                                                                             // that does not interfere with the main body text's flow. 
                                                                                             // Inserting a footnote/endnote adds a small superscript reference symbol
                                                                                             // at the main body text where we insert the footnote/endnote.
                                                                                             // Each footnote/endnote also creates an entry, which consists of a symbol that matches the reference
                                                                                             // symbol in the main body text. The reference text that we pass to the document builder's "InsertEndnote" method.
                                                                                             // Footnote entries, by default, show up at the bottom of each page that contains
                                                                                             // their reference symbols, and endnotes show up at the end of the document.
                                                                                             builder.Write("Text 1. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 1.");
                                                                                             builder.Write("Text 2. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 2.");
                                                                                             builder.InsertBreak(BreakType.PageBreak);
                                                                                             builder.Write("Text 3. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 3.");
                                                                                             builder.Write("Text 4. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 4.");

                                                                                             builder.InsertBreak(BreakType.PageBreak);

                                                                                             builder.Write("Text 1. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 1.");
                                                                                             builder.Write("Text 2. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 2.");
                                                                                             builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                                                             builder.Write("Text 3. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 3.");
                                                                                             builder.Write("Text 4. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 4.");

                                                                                             // By default, the reference symbol for each footnote and endnote is its index
                                                                                             // among all the document's footnotes/endnotes. Each document maintains separate counts
                                                                                             // for footnotes and endnotes and does not restart these counts at any point.
                                                                                             Assert.That(FootnoteNumberingRule.Default, Is.EqualTo(doc.FootnoteOptions.RestartRule));
                                                                                             Assert.That(FootnoteNumberingRule.Continuous, Is.EqualTo(FootnoteNumberingRule.Default));

                                                                                             // We can use the "RestartRule" property to get the document to restart
                                                                                             // the footnote/endnote counts at a new page or section.
                                                                                             doc.FootnoteOptions.RestartRule = FootnoteNumberingRule.RestartPage;
                                                                                             doc.EndnoteOptions.RestartRule = FootnoteNumberingRule.RestartSection;

                                                                                             doc.Save(ArtifactsDir + "InlineStory.NumberingRule.docx");

FieldOptions

Gets a Aspose.Words.Fields.FieldOptions object that represents options to control field handling in the document.

public FieldOptions FieldOptions { get; }

Property Value

FieldOptions

Examples

Shows how to specify the source of the culture used for date formatting during a field update or mail merge.

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

                                                                                                                       // Insert two merge fields with German locale.
                                                                                                                       builder.Font.LocaleId = new CultureInfo("de-DE").LCID;
                                                                                                                       builder.InsertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
                                                                                                                       builder.Write(" - ");
                                                                                                                       builder.InsertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");

                                                                                                                       // Set the current culture to US English after preserving its original value in a variable.
                                                                                                                       CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
                                                                                                                       Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

                                                                                                                       // This merge will use the current thread's culture to format the date, US English.
                                                                                                                       doc.MailMerge.Execute(new[] { "Date1" }, new object[] { new DateTime(2020, 1, 01) });

                                                                                                                       // Configure the next merge to source its culture value from the field code. The value of that culture will be German.
                                                                                                                       doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
                                                                                                                       doc.MailMerge.Execute(new[] { "Date2" }, new object[] { new DateTime(2020, 1, 01) });

                                                                                                                       // The first merge result contains a date formatted in English, while the second one is in German.
                                                                                                                       Assert.That(doc.Range.Text.Trim(), Is.EqualTo("Wednesday, 1 January 2020 - Mittwoch, 1 Januar 2020"));

                                                                                                                       // Restore the thread's original culture.
                                                                                                                       Thread.CurrentThread.CurrentCulture = currentCulture;

FirstSection

Gets the first section in the document.

public Section FirstSection { get; }

Property Value

Section

Examples

Shows how to replace text in a document’s footer.

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

                                                            HeaderFooterCollection headersFooters = doc.FirstSection.HeadersFooters;
                                                            HeaderFooter footer = headersFooters[HeaderFooterType.FooterPrimary];

                                                            FindReplaceOptions options = new FindReplaceOptions
                                                            {
                                                                MatchCase = false,
                                                                FindWholeWordsOnly = false
                                                            };

                                                            int currentYear = DateTime.Now.Year;
                                                            footer.Range.Replace("(C) 2006 Aspose Pty Ltd.", $"Copyright (C) {currentYear} by Aspose Pty Ltd.", options);

                                                            doc.Save(ArtifactsDir + "HeaderFooter.ReplaceText.docx");

Shows how to create a new section with a document builder.

Document doc = new Document();

                                                                     // A blank document contains one section by default,
                                                                     // which contains child nodes that we can edit.
                                                                     Assert.That(doc.Sections.Count, Is.EqualTo(1));

                                                                     // Use a document builder to add text to the first section.
                                                                     DocumentBuilder builder = new DocumentBuilder(doc);
                                                                     builder.Writeln("Hello world!");

                                                                     // Create a second section by inserting a section break.
                                                                     builder.InsertBreak(BreakType.SectionBreakNewPage);

                                                                     Assert.That(doc.Sections.Count, Is.EqualTo(2));

                                                                     // Each section has its own page setup settings.
                                                                     // We can split the text in the second section into two columns.
                                                                     // This will not affect the text in the first section.
                                                                     doc.LastSection.PageSetup.TextColumns.SetCount(2);
                                                                     builder.Writeln("Column 1.");
                                                                     builder.InsertBreak(BreakType.ColumnBreak);
                                                                     builder.Writeln("Column 2.");

                                                                     Assert.That(doc.FirstSection.PageSetup.TextColumns.Count, Is.EqualTo(1));
                                                                     Assert.That(doc.LastSection.PageSetup.TextColumns.Count, Is.EqualTo(2));

                                                                     doc.Save(ArtifactsDir + "Section.Create.docx");

Shows how to iterate through the children of a composite node.

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

                                                                         builder.Write("Section 1");
                                                                         builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
                                                                         builder.Write("Primary header");
                                                                         builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
                                                                         builder.Write("Primary footer");

                                                                         Section section = doc.FirstSection;

                                                                         // A Section is a composite node and can contain child nodes,
                                                                         // but only if those child nodes are of a "Body" or "HeaderFooter" node type.
                                                                         foreach (Node node in section)
                                                                         {
                                                                             switch (node.NodeType)
                                                                             {
                                                                                 case NodeType.Body:
                                                                                 {
                                                                                     Body body = (Body)node;

                                                                                     Console.WriteLine("Body:");
                                                                                     Console.WriteLine($"\t\"{body.GetText().Trim()}\"");
                                                                                     break;
                                                                                 }
                                                                                 case NodeType.HeaderFooter:
                                                                                 {
                                                                                     HeaderFooter headerFooter = (HeaderFooter)node;

                                                                                     Console.WriteLine($"HeaderFooter type: {headerFooter.HeaderFooterType}:");
                                                                                     Console.WriteLine($"\t\"{headerFooter.GetText().Trim()}\"");
                                                                                     break;
                                                                                 }
                                                                                 default:
                                                                                 {
                                                                                     throw new Exception("Unexpected node type in a section.");
                                                                                 }
                                                                             }
                                                                         }

Remarks

Returns null if there are no sections.

FontSettings

Gets or sets document font settings.

public FontSettings FontSettings { get; set; }

Property Value

FontSettings

Examples

Shows how set font substitution rules.

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

                                                 builder.Font.Name = "Arial";
                                                 builder.Writeln("Hello world!");
                                                 builder.Font.Name = "Amethysta";
                                                 builder.Writeln("The quick brown fox jumps over the lazy dog.");

                                                 FontSourceBase[] fontSources = FontSettings.DefaultInstance.GetFontsSources();

                                                 // The default font sources contain the first font that the document uses.
                                                 Assert.That(fontSources.Length, Is.EqualTo(1));
                                                 Assert.That(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial"), Is.True);

                                                 // The second font, "Amethysta", is unavailable.
                                                 Assert.That(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Amethysta"), Is.False);

                                                 // We can configure a font substitution table which determines
                                                 // which fonts Aspose.Words will use as substitutes for unavailable fonts.
                                                 // Set two substitution fonts for "Amethysta": "Arvo", and "Courier New".
                                                 // If the first substitute is unavailable, Aspose.Words attempts to use the second substitute, and so on.
                                                 doc.FontSettings = new FontSettings();
                                                 doc.FontSettings.SubstitutionSettings.TableSubstitution.SetSubstitutes(
                                                     "Amethysta", new[] {"Arvo", "Courier New"});

                                                 // "Amethysta" is unavailable, and the substitution rule states that the first font to use as a substitute is "Arvo".
                                                 Assert.That(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arvo"), Is.False);

                                                 // "Arvo" is also unavailable, but "Courier New" is.
                                                 Assert.That(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Courier New"), Is.True);

                                                 // The output document will display the text that uses the "Amethysta" font formatted with "Courier New".
                                                 doc.Save(ArtifactsDir + "FontSettings.TableSubstitution.pdf");

Remarks

This property allows to specify font settings per document. If set to null, default static font settings Aspose.Words.Fonts.FontSettings.DefaultInstance will be used.

The default value is null.

FootnoteOptions

Provides options that control numbering and positioning of footnotes in this document.

public FootnoteOptions FootnoteOptions { get; }

Property Value

FootnoteOptions

Examples

Shows how to select a different place where the document collects and displays its footnotes.

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

                                                                                                        // A footnote is a way to attach a reference or a side comment to text
                                                                                                        // that does not interfere with the main body text's flow.  
                                                                                                        // Inserting a footnote adds a small superscript reference symbol
                                                                                                        // at the main body text where we insert the footnote.
                                                                                                        // Each footnote also creates an entry at the bottom of the page, consisting of a symbol
                                                                                                        // that matches the reference symbol in the main body text.
                                                                                                        // The reference text that we pass to the document builder's "InsertFootnote" method.
                                                                                                        builder.Write("Hello world!");
                                                                                                        builder.InsertFootnote(FootnoteType.Footnote, "Footnote contents.");

                                                                                                        // We can use the "Position" property to determine where the document will place all its footnotes.
                                                                                                        // If we set the value of the "Position" property to "FootnotePosition.BottomOfPage",
                                                                                                        // every footnote will show up at the bottom of the page that contains its reference mark. This is the default value.
                                                                                                        // If we set the value of the "Position" property to "FootnotePosition.BeneathText",
                                                                                                        // every footnote will show up at the end of the page's text that contains its reference mark.
                                                                                                        doc.FootnoteOptions.Position = footnotePosition;

                                                                                                        doc.Save(ArtifactsDir + "InlineStory.PositionFootnote.docx");

Shows how to set a number at which the document begins the footnote/endnote count.

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

                                                                                             // Footnotes and endnotes are a way to attach a reference or a side comment to text
                                                                                             // that does not interfere with the main body text's flow. 
                                                                                             // Inserting a footnote/endnote adds a small superscript reference symbol
                                                                                             // at the main body text where we insert the footnote/endnote.
                                                                                             // Each footnote/endnote also creates an entry, which consists of a symbol
                                                                                             // that matches the reference symbol in the main body text.
                                                                                             // The reference text that we pass to the document builder's "InsertEndnote" method.
                                                                                             // Footnote entries, by default, show up at the bottom of each page that contains
                                                                                             // their reference symbols, and endnotes show up at the end of the document.
                                                                                             builder.Write("Text 1. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 1.");
                                                                                             builder.Write("Text 2. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 2.");
                                                                                             builder.Write("Text 3. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 3.");

                                                                                             builder.InsertParagraph();

                                                                                             builder.Write("Text 1. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 1.");
                                                                                             builder.Write("Text 2. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 2.");
                                                                                             builder.Write("Text 3. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 3.");

                                                                                             // By default, the reference symbol for each footnote and endnote is its index
                                                                                             // among all the document's footnotes/endnotes. Each document maintains separate counts
                                                                                             // for footnotes and for endnotes, which both begin at 1.
                                                                                             Assert.That(doc.FootnoteOptions.StartNumber, Is.EqualTo(1));
                                                                                             Assert.That(doc.EndnoteOptions.StartNumber, Is.EqualTo(1));

                                                                                             // We can use the "StartNumber" property to get the document to
                                                                                             // begin a footnote or endnote count at a different number.
                                                                                             doc.EndnoteOptions.NumberStyle = NumberStyle.Arabic;
                                                                                             doc.EndnoteOptions.StartNumber = 50;

                                                                                             doc.Save(ArtifactsDir + "InlineStory.StartNumber.docx");

Shows how to change the number style of footnote/endnote reference marks.

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

                                                                                    // Footnotes and endnotes are a way to attach a reference or a side comment to text
                                                                                    // that does not interfere with the main body text's flow. 
                                                                                    // Inserting a footnote/endnote adds a small superscript reference symbol
                                                                                    // at the main body text where we insert the footnote/endnote.
                                                                                    // Each footnote/endnote also creates an entry, which consists of a symbol that matches the reference
                                                                                    // symbol in the main body text. The reference text that we pass to the document builder's "InsertEndnote" method.
                                                                                    // Footnote entries, by default, show up at the bottom of each page that contains
                                                                                    // their reference symbols, and endnotes show up at the end of the document.
                                                                                    builder.Write("Text 1. ");
                                                                                    builder.InsertFootnote(FootnoteType.Footnote, "Footnote 1.");
                                                                                    builder.Write("Text 2. ");
                                                                                    builder.InsertFootnote(FootnoteType.Footnote, "Footnote 2.");
                                                                                    builder.Write("Text 3. ");
                                                                                    builder.InsertFootnote(FootnoteType.Footnote, "Footnote 3.", "Custom footnote reference mark");

                                                                                    builder.InsertParagraph();

                                                                                    builder.Write("Text 1. ");
                                                                                    builder.InsertFootnote(FootnoteType.Endnote, "Endnote 1.");
                                                                                    builder.Write("Text 2. ");
                                                                                    builder.InsertFootnote(FootnoteType.Endnote, "Endnote 2.");
                                                                                    builder.Write("Text 3. ");
                                                                                    builder.InsertFootnote(FootnoteType.Endnote, "Endnote 3.", "Custom endnote reference mark");

                                                                                    // By default, the reference symbol for each footnote and endnote is its index
                                                                                    // among all the document's footnotes/endnotes. Each document maintains separate counts
                                                                                    // for footnotes and for endnotes. By default, footnotes display their numbers using Arabic numerals,
                                                                                    // and endnotes display their numbers in lowercase Roman numerals.
                                                                                    Assert.That(doc.FootnoteOptions.NumberStyle, Is.EqualTo(NumberStyle.Arabic));
                                                                                    Assert.That(doc.EndnoteOptions.NumberStyle, Is.EqualTo(NumberStyle.LowercaseRoman));

                                                                                    // We can use the "NumberStyle" property to apply custom numbering styles to footnotes and endnotes.
                                                                                    // This will not affect footnotes/endnotes with custom reference marks.
                                                                                    doc.FootnoteOptions.NumberStyle = NumberStyle.UppercaseRoman;
                                                                                    doc.EndnoteOptions.NumberStyle = NumberStyle.UppercaseLetter;

                                                                                    doc.Save(ArtifactsDir + "InlineStory.RefMarkNumberStyle.docx");

Shows how to restart footnote/endnote numbering at certain places in the document.

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

                                                                                             // Footnotes and endnotes are a way to attach a reference or a side comment to text
                                                                                             // that does not interfere with the main body text's flow. 
                                                                                             // Inserting a footnote/endnote adds a small superscript reference symbol
                                                                                             // at the main body text where we insert the footnote/endnote.
                                                                                             // Each footnote/endnote also creates an entry, which consists of a symbol that matches the reference
                                                                                             // symbol in the main body text. The reference text that we pass to the document builder's "InsertEndnote" method.
                                                                                             // Footnote entries, by default, show up at the bottom of each page that contains
                                                                                             // their reference symbols, and endnotes show up at the end of the document.
                                                                                             builder.Write("Text 1. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 1.");
                                                                                             builder.Write("Text 2. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 2.");
                                                                                             builder.InsertBreak(BreakType.PageBreak);
                                                                                             builder.Write("Text 3. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 3.");
                                                                                             builder.Write("Text 4. ");
                                                                                             builder.InsertFootnote(FootnoteType.Footnote, "Footnote 4.");

                                                                                             builder.InsertBreak(BreakType.PageBreak);

                                                                                             builder.Write("Text 1. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 1.");
                                                                                             builder.Write("Text 2. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 2.");
                                                                                             builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                                                             builder.Write("Text 3. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 3.");
                                                                                             builder.Write("Text 4. ");
                                                                                             builder.InsertFootnote(FootnoteType.Endnote, "Endnote 4.");

                                                                                             // By default, the reference symbol for each footnote and endnote is its index
                                                                                             // among all the document's footnotes/endnotes. Each document maintains separate counts
                                                                                             // for footnotes and endnotes and does not restart these counts at any point.
                                                                                             Assert.That(FootnoteNumberingRule.Default, Is.EqualTo(doc.FootnoteOptions.RestartRule));
                                                                                             Assert.That(FootnoteNumberingRule.Continuous, Is.EqualTo(FootnoteNumberingRule.Default));

                                                                                             // We can use the "RestartRule" property to get the document to restart
                                                                                             // the footnote/endnote counts at a new page or section.
                                                                                             doc.FootnoteOptions.RestartRule = FootnoteNumberingRule.RestartPage;
                                                                                             doc.EndnoteOptions.RestartRule = FootnoteNumberingRule.RestartSection;

                                                                                             doc.Save(ArtifactsDir + "InlineStory.NumberingRule.docx");

Frameset

Returns a Aspose.Words.Document.Frameset instance if this document represents a frames page.

public Frameset Frameset { get; }

Property Value

Frameset

Examples

Shows how to access frames on-page.

// Document contains several frames with links to other documents.
                                              Document doc = new Document(MyDir + "Frameset.docx");

                                              Assert.That(doc.Frameset.ChildFramesets.Count, Is.EqualTo(3));
                                              // We can check the default URL (a web page URL or local document) or if the frame is an external resource.
                                              Assert.That(doc.Frameset.ChildFramesets[0].ChildFramesets[0].FrameDefaultUrl, Is.EqualTo("https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.docx"));
                                              Assert.That(doc.Frameset.ChildFramesets[0].ChildFramesets[0].IsFrameLinkToFile, Is.True);

                                              Assert.That(doc.Frameset.ChildFramesets[1].FrameDefaultUrl, Is.EqualTo("Document.docx"));
                                              Assert.That(doc.Frameset.ChildFramesets[1].IsFrameLinkToFile, Is.False);

                                              // Change properties for one of our frames.
                                              doc.Frameset.ChildFramesets[0].ChildFramesets[0].FrameDefaultUrl =
                                                  "https://github.com/aspose-words/Aspose.Words-for-.NET/blob/master/Examples/Data/Absolute%20position%20tab.docx";
                                              doc.Frameset.ChildFramesets[0].ChildFramesets[0].IsFrameLinkToFile = false;

Remarks

If the document is not framed, the property has the null value.

GlossaryDocument

Gets or sets the glossary document within this document or template. A glossary document is a storage for AutoText, AutoCorrect and Building Block entries defined in a document.

public GlossaryDocument GlossaryDocument { get; set; }

Property Value

GlossaryDocument

Examples

Shows how to add a custom building block to a document.

public void CreateAndInsert()
                                                                  {
                                                                      // A document's glossary document stores building blocks.
                                                                      Document doc = new Document();
                                                                      GlossaryDocument glossaryDoc = new GlossaryDocument();
                                                                      doc.GlossaryDocument = glossaryDoc;

                                                                      // Create a building block, name it, and then add it to the glossary document.
                                                                      BuildingBlock block = new BuildingBlock(glossaryDoc)
                                                                      {
                                                                          Name = "Custom Block"
                                                                      };

                                                                      glossaryDoc.AppendChild(block);

                                                                      // All new building block GUIDs have the same zero value by default, and we can give them a new unique value.
                                                                      Assert.That(block.Guid.ToString(), Is.EqualTo("00000000-0000-0000-0000-000000000000"));

                                                                      block.Guid = Guid.NewGuid();

                                                                      // The following properties categorize building blocks
                                                                      // in the menu we can access in Microsoft Word via "Insert" -> "Quick Parts" -> "Building Blocks Organizer".
                                                                      Assert.That(block.Category, Is.EqualTo("(Empty Category)"));
                                                                      Assert.That(block.Type, Is.EqualTo(BuildingBlockType.None));
                                                                      Assert.That(block.Gallery, Is.EqualTo(BuildingBlockGallery.All));
                                                                      Assert.That(block.Behavior, Is.EqualTo(BuildingBlockBehavior.Content));

                                                                      // Before we can add this building block to our document, we will need to give it some contents,
                                                                      // which we will do using a document visitor. This visitor will also set a category, gallery, and behavior.
                                                                      BuildingBlockVisitor visitor = new BuildingBlockVisitor(glossaryDoc);
                                                                      // Visit start/end of the BuildingBlock.
                                                                      block.Accept(visitor);

                                                                      // We can access the block that we just made from the glossary document.
                                                                      BuildingBlock customBlock = glossaryDoc.GetBuildingBlock(BuildingBlockGallery.QuickParts,
                                                                          "My custom building blocks", "Custom Block");

                                                                      // The block itself is a section that contains the text.
                                                                      Assert.That(customBlock.FirstSection.Body.FirstParagraph.GetText(), Is.EqualTo($"Text inside {customBlock.Name}\f"));
                                                                      Assert.That(customBlock.LastSection, Is.EqualTo(customBlock.FirstSection));
                                                                      // Now, we can insert it into the document as a new section.
                                                                      doc.AppendChild(doc.ImportNode(customBlock.FirstSection, true));

                                                                      // We can also find it in Microsoft Word's Building Blocks Organizer and place it manually.
                                                                      doc.Save(ArtifactsDir + "BuildingBlocks.CreateAndInsert.dotx");
                                                                  }

                                                                  /// <summary>
                                                                  /// Sets up a visited building block to be inserted into the document as a quick part and adds text to its contents.
                                                                  /// </summary>
                                                                  public class BuildingBlockVisitor : DocumentVisitor
                                                                  {
                                                                      public BuildingBlockVisitor(GlossaryDocument ownerGlossaryDoc)
                                                                      {
                                                                          mBuilder = new StringBuilder();
                                                                          mGlossaryDoc = ownerGlossaryDoc;
                                                                      }

                                                                      public override VisitorAction VisitBuildingBlockStart(BuildingBlock block)
                                                                      {
                                                                          // Configure the building block as a quick part, and add properties used by Building Blocks Organizer.
                                                                          block.Behavior = BuildingBlockBehavior.Paragraph;
                                                                          block.Category = "My custom building blocks";
                                                                          block.Description =
                                                                              "Using this block in the Quick Parts section of word will place its contents at the cursor.";
                                                                          block.Gallery = BuildingBlockGallery.QuickParts;

                                                                          // Add a section with text.
                                                                          // Inserting the block into the document will append this section with its child nodes at the location.
                                                                          Section section = new Section(mGlossaryDoc);
                                                                          block.AppendChild(section);
                                                                          block.FirstSection.EnsureMinimum();

                                                                          Run run = new Run(mGlossaryDoc, "Text inside " + block.Name);
                                                                          block.FirstSection.Body.FirstParagraph.AppendChild(run);

                                                                          return VisitorAction.Continue;
                                                                      }

                                                                      public override VisitorAction VisitBuildingBlockEnd(BuildingBlock block)
                                                                      {
                                                                          mBuilder.Append("Visited " + block.Name + "\r\n");
                                                                          return VisitorAction.Continue;
                                                                      }

                                                                      private readonly StringBuilder mBuilder;
                                                                      private readonly GlossaryDocument mGlossaryDoc;
                                                                  }

Remarks

This property returns null if the document does not have a glossary document.

You can add a glossary document to a document by creating a Aspose.Words.BuildingBlocks.GlossaryDocument object and assigning to this property.

Aspose.Words.BuildingBlocks.GlossaryDocument

GrammarChecked

Returns true if the document has been checked for grammar.

public bool GrammarChecked { get; set; }

Property Value

bool

Examples

Shows how to set spelling or grammar verifying.

Document doc = new Document();

                                                          // The string with spelling errors.
                                                          doc.FirstSection.Body.FirstParagraph.Runs.Add(new Run(doc, "The speeling in this documentz is all broked."));

                                                          // Spelling/Grammar check start if we set properties to false.
                                                          // We can see all errors in Microsoft Word via Review -> Spelling & Grammar.
                                                          // Note that Microsoft Word does not start grammar/spell check automatically for DOC and RTF document format.
                                                          doc.SpellingChecked = checkSpellingGrammar;
                                                          doc.GrammarChecked = checkSpellingGrammar;

                                                          doc.Save(ArtifactsDir + "Document.SpellingOrGrammar.docx");

Remarks

To recheck the grammar in the document, set this property to false.

HasMacros

Returns true if the document has a VBA project (macros).

public bool HasMacros { get; }

Property Value

bool

Examples

Shows how to use MACROBUTTON fields to allow us to run a document’s macros by clicking.

Document doc = new Document(MyDir + "Macro.docm");
                                                                                                  DocumentBuilder builder = new DocumentBuilder(doc);

                                                                                                  Assert.That(doc.HasMacros, Is.True);

                                                                                                  // Insert a MACROBUTTON field, and reference one of the document's macros by name in the MacroName property.
                                                                                                  FieldMacroButton field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
                                                                                                  field.MacroName = "MyMacro";
                                                                                                  field.DisplayText = "Double click to run macro: " + field.MacroName;

                                                                                                  Assert.That(field.GetFieldCode(), Is.EqualTo(" MACROBUTTON  MyMacro Double click to run macro: MyMacro"));

                                                                                                  // Use the property to reference "ViewZoom200", a macro that ships with Microsoft Word.
                                                                                                  // We can find all other macros via View -> Macros (dropdown) -> View Macros.
                                                                                                  // In that menu, select "Word Commands" from the "Macros in:" drop down.
                                                                                                  // If our document contains a custom macro with the same name as a stock macro,
                                                                                                  // our macro will be the one that the MACROBUTTON field runs.
                                                                                                  builder.InsertParagraph();
                                                                                                  field = (FieldMacroButton)builder.InsertField(FieldType.FieldMacroButton, true);
                                                                                                  field.MacroName = "ViewZoom200";
                                                                                                  field.DisplayText = "Run " + field.MacroName;

                                                                                                  Assert.That(field.GetFieldCode(), Is.EqualTo(" MACROBUTTON  ViewZoom200 Run ViewZoom200"));

                                                                                                  // Save the document as a macro-enabled document type.
                                                                                                  doc.Save(ArtifactsDir + "Field.MACROBUTTON.docm");

See Also

Document . RemoveMacros ()

HasRevisions

Returns true if the document has any tracked changes.

public bool HasRevisions { get; }

Property Value

bool

Examples

Shows how to work with revisions in a document.

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

                                                          // Normal editing of the document does not count as a revision.
                                                          builder.Write("This does not count as a revision. ");

                                                          Assert.That(doc.HasRevisions, Is.False);

                                                          // To register our edits as revisions, we need to declare an author, and then start tracking them.
                                                          doc.StartTrackRevisions("John Doe", DateTime.Now);

                                                          builder.Write("This is revision #1. ");

                                                          Assert.That(doc.HasRevisions, Is.True);
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(1));

                                                          // This flag corresponds to the "Review" -> "Tracking" -> "Track Changes" option in Microsoft Word.
                                                          // The "StartTrackRevisions" method does not affect its value,
                                                          // and the document is tracking revisions programmatically despite it having a value of "false".
                                                          // If we open this document using Microsoft Word, it will not be tracking revisions.
                                                          Assert.That(doc.TrackRevisions, Is.False);

                                                          // We have added text using the document builder, so the first revision is an insertion-type revision.
                                                          Revision revision = doc.Revisions[0];
                                                          Assert.That(revision.Author, Is.EqualTo("John Doe"));
                                                          Assert.That(revision.ParentNode.GetText(), Is.EqualTo("This is revision #1. "));
                                                          Assert.That(revision.RevisionType, Is.EqualTo(RevisionType.Insertion));
                                                          Assert.That(DateTime.Now.Date, Is.EqualTo(revision.DateTime.Date));
                                                          Assert.That(revision.Group, Is.EqualTo(doc.Revisions.Groups[0]));

                                                          // Remove a run to create a deletion-type revision.
                                                          doc.FirstSection.Body.FirstParagraph.Runs[0].Remove();

                                                          // Adding a new revision places it at the beginning of the revision collection.
                                                          Assert.That(doc.Revisions[0].RevisionType, Is.EqualTo(RevisionType.Deletion));
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(2));

                                                          // Insert revisions show up in the document body even before we accept/reject the revision.
                                                          // Rejecting the revision will remove its nodes from the body. Conversely, nodes that make up delete revisions
                                                          // also linger in the document until we accept the revision.
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This does not count as a revision. This is revision #1."));

                                                          // Accepting the delete revision will remove its parent node from the paragraph text
                                                          // and then remove the collection's revision itself.
                                                          doc.Revisions[0].Accept();

                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #1."));

                                                          builder.Writeln("");
                                                          builder.Write("This is revision #2.");

                                                          // Now move the node to create a moving revision type.
                                                          Node node = doc.FirstSection.Body.Paragraphs[1];
                                                          Node endNode = doc.FirstSection.Body.Paragraphs[1].NextSibling;
                                                          Node referenceNode = doc.FirstSection.Body.Paragraphs[0];

                                                          while (node != endNode)
                                                          {
                                                              Node nextNode = node.NextSibling;
                                                              doc.FirstSection.Body.InsertBefore(node, referenceNode);
                                                              node = nextNode;
                                                          }

                                                          Assert.That(doc.Revisions[0].RevisionType, Is.EqualTo(RevisionType.Moving));
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(8));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #2.\rThis is revision #1. \rThis is revision #2."));

                                                          // The moving revision is now at index 1. Reject the revision to discard its contents.
                                                          doc.Revisions[1].Reject();

                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(6));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #1. \rThis is revision #2."));

Remarks

This property is a shortcut for comparing Aspose.Words.RevisionCollection.Count to zero.

HyphenationOptions

Provides access to document hyphenation options.

public HyphenationOptions HyphenationOptions { get; }

Property Value

HyphenationOptions

Examples

Shows how to configure automatic hyphenation.

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

                                                        builder.Font.Size = 24;
                                                        builder.Writeln("Lorem ipsum dolor sit amet, consectetur adipiscing elit, " +
                                                                        "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");

                                                        doc.HyphenationOptions.AutoHyphenation = true;
                                                        doc.HyphenationOptions.ConsecutiveHyphenLimit = 2;
                                                        doc.HyphenationOptions.HyphenationZone = 720;
                                                        doc.HyphenationOptions.HyphenateCaps = true;

                                                        doc.Save(ArtifactsDir + "Document.HyphenationOptions.docx");

IncludeTextboxesFootnotesEndnotesInStat

Specifies whether to include textboxes, footnotes and endnotes in word count statistics.

public bool IncludeTextboxesFootnotesEndnotesInStat { get; set; }

Property Value

bool

Examples

Shows how to include or exclude textboxes, footnotes and endnotes from word count statistics.

Document doc = new Document();
                                                                                                        DocumentBuilder builder = new DocumentBuilder(doc);
                                                                                                        builder.Writeln("Lorem ipsum");
                                                                                                        builder.InsertFootnote(FootnoteType.Footnote, "sit amet");

                                                                                                        // By default option is set to 'false'.
                                                                                                        doc.UpdateWordCount();
                                                                                                        // Words count without textboxes, footnotes and endnotes.
                                                                                                        Assert.That(doc.BuiltInDocumentProperties.Words, Is.EqualTo(2));

                                                                                                        doc.IncludeTextboxesFootnotesEndnotesInStat = true;
                                                                                                        doc.UpdateWordCount();
                                                                                                        // Words count with textboxes, footnotes and endnotes.
                                                                                                        Assert.That(doc.BuiltInDocumentProperties.Words, Is.EqualTo(4));

JustificationMode

Gets or sets the character spacing adjustment of a document.

public JustificationMode JustificationMode { get; set; }

Property Value

JustificationMode

Examples

Shows how to manage character spacing control.

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

                                                         JustificationMode justificationMode = doc.JustificationMode;
                                                         if (justificationMode == JustificationMode.Expand)
                                                             doc.JustificationMode = JustificationMode.Compress;

                                                         doc.Save(ArtifactsDir + "Document.SetJustificationMode.docx");

LastSection

Gets the last section in the document.

public Section LastSection { get; }

Property Value

Section

Examples

Shows how to create a new section with a document builder.

Document doc = new Document();

                                                                     // A blank document contains one section by default,
                                                                     // which contains child nodes that we can edit.
                                                                     Assert.That(doc.Sections.Count, Is.EqualTo(1));

                                                                     // Use a document builder to add text to the first section.
                                                                     DocumentBuilder builder = new DocumentBuilder(doc);
                                                                     builder.Writeln("Hello world!");

                                                                     // Create a second section by inserting a section break.
                                                                     builder.InsertBreak(BreakType.SectionBreakNewPage);

                                                                     Assert.That(doc.Sections.Count, Is.EqualTo(2));

                                                                     // Each section has its own page setup settings.
                                                                     // We can split the text in the second section into two columns.
                                                                     // This will not affect the text in the first section.
                                                                     doc.LastSection.PageSetup.TextColumns.SetCount(2);
                                                                     builder.Writeln("Column 1.");
                                                                     builder.InsertBreak(BreakType.ColumnBreak);
                                                                     builder.Writeln("Column 2.");

                                                                     Assert.That(doc.FirstSection.PageSetup.TextColumns.Count, Is.EqualTo(1));
                                                                     Assert.That(doc.LastSection.PageSetup.TextColumns.Count, Is.EqualTo(2));

                                                                     doc.Save(ArtifactsDir + "Section.Create.docx");

Remarks

Returns null if there are no sections.

LayoutOptions

Gets a Aspose.Words.Layout.LayoutOptions object that represents options to control the layout process of this document.

public LayoutOptions LayoutOptions { get; }

Property Value

LayoutOptions

Examples

Shows how to hide text in a rendered output document.

Document doc = new Document();
                                                                DocumentBuilder builder = new DocumentBuilder(doc);
                                                                // Insert hidden text, then specify whether we wish to omit it from a rendered document.
                                                                builder.Writeln("This text is not hidden.");
                                                                builder.Font.Hidden = true;
                                                                builder.Writeln("This text is hidden.");

                                                                doc.LayoutOptions.ShowHiddenText = showHiddenText;

                                                                doc.Save(ArtifactsDir + "Document.LayoutOptionsHiddenText.pdf");

Shows how to show paragraph marks in a rendered output document.

Document doc = new Document();
                                                                           DocumentBuilder builder = new DocumentBuilder(doc);
                                                                           // Add some paragraphs, then enable paragraph marks to show the ends of paragraphs
                                                                           // with a pilcrow (¶) symbol when we render the document.
                                                                           builder.Writeln("Hello world!");
                                                                           builder.Writeln("Hello again!");

                                                                           doc.LayoutOptions.ShowParagraphMarks = showParagraphMarks;

                                                                           doc.Save(ArtifactsDir + "Document.LayoutOptionsParagraphMarks.pdf");

Shows how to alter the appearance of revisions in a rendered output document.

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

                                                                                        // Insert a revision, then change the color of all revisions to green.
                                                                                        builder.Writeln("This is not a revision.");
                                                                                        doc.StartTrackRevisions("John Doe", DateTime.Now);
                                                                                        builder.Writeln("This is a revision.");
                                                                                        doc.StopTrackRevisions();
                                                                                        builder.Writeln("This is not a revision.");

                                                                                        // Remove the bar that appears to the left of every revised line.
                                                                                        doc.LayoutOptions.RevisionOptions.InsertedTextColor = RevisionColor.BrightGreen;
                                                                                        doc.LayoutOptions.RevisionOptions.ShowRevisionBars = false;
                                                                                        doc.LayoutOptions.RevisionOptions.RevisionBarsPosition = HorizontalAlignment.Right;

                                                                                        doc.Save(ArtifactsDir + "Revision.LayoutOptionsRevisions.pdf");

MailMerge

Returns a Aspose.Words.MailMerging.MailMerge object that represents the mail merge functionality for the document.

public MailMerge MailMerge { get; }

Property Value

MailMerge

Examples

Shows how to execute a mail merge with data from a DataTable.

public void ExecuteDataTable()
                                                                        {
                                                                            DataTable table = new DataTable("Test");
                                                                            table.Columns.Add("CustomerName");
                                                                            table.Columns.Add("Address");
                                                                            table.Rows.Add(new object[] { "Thomas Hardy", "120 Hanover Sq., London" });
                                                                            table.Rows.Add(new object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

                                                                            // Below are two ways of using a DataTable as the data source for a mail merge.
                                                                            // 1 -  Use the entire table for the mail merge to create one output mail merge document for every row in the table:
                                                                            Document doc = CreateSourceDocExecuteDataTable();

                                                                            doc.MailMerge.Execute(table);

                                                                            doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.WholeTable.docx");

                                                                            // 2 -  Use one row of the table to create one output mail merge document:
                                                                            doc = CreateSourceDocExecuteDataTable();

                                                                            doc.MailMerge.Execute(table.Rows[1]);

                                                                            doc.Save(ArtifactsDir + "MailMerge.ExecuteDataTable.OneRow.docx");
                                                                        }

                                                                        /// <summary>
                                                                        /// Creates a mail merge source document.
                                                                        /// </summary>
                                                                        private static Document CreateSourceDocExecuteDataTable()
                                                                        {
                                                                            Document doc = new Document();
                                                                            DocumentBuilder builder = new DocumentBuilder(doc);

                                                                            builder.InsertField(" MERGEFIELD CustomerName ");
                                                                            builder.InsertParagraph();
                                                                            builder.InsertField(" MERGEFIELD Address ");

                                                                            return doc;
                                                                        }

MailMergeSettings

Gets or sets the object that contains all of the mail merge information for a document.

public MailMergeSettings MailMergeSettings { get; set; }

Property Value

MailMergeSettings

Examples

Shows how to execute a mail merge with data from an Office Data Source Object.

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

                                                                                         builder.Write("Dear ");
                                                                                         builder.InsertField("MERGEFIELD FirstName", "<FirstName>");
                                                                                         builder.Write(" ");
                                                                                         builder.InsertField("MERGEFIELD LastName", "<LastName>");
                                                                                         builder.Writeln(": ");
                                                                                         builder.InsertField("MERGEFIELD Message", "<Message>");

                                                                                         // Create a data source in the form of an ASCII file, with the "|" character
                                                                                         // acting as the delimiter that separates columns. The first line contains the three columns' names,
                                                                                         // and each subsequent line is a row with their respective values.
                                                                                         string[] lines = { "FirstName|LastName|Message",
                                                                                             "John|Doe|Hello! This message was created with Aspose Words mail merge." };
                                                                                         string dataSrcFilename = ArtifactsDir + "MailMerge.MailMergeSettings.DataSource.txt";

                                                                                         File.WriteAllLines(dataSrcFilename, lines);

                                                                                         MailMergeSettings settings = doc.MailMergeSettings;
                                                                                         settings.MainDocumentType = MailMergeMainDocumentType.MailingLabels;
                                                                                         settings.CheckErrors = MailMergeCheckErrors.Simulate;
                                                                                         settings.DataType = MailMergeDataType.Native;
                                                                                         settings.DataSource = dataSrcFilename;
                                                                                         settings.Query = "SELECT * FROM " + doc.MailMergeSettings.DataSource;
                                                                                         settings.LinkToQuery = true;
                                                                                         settings.ViewMergedData = true;

                                                                                         Assert.That(settings.Destination, Is.EqualTo(MailMergeDestination.Default));
                                                                                         Assert.That(settings.DoNotSupressBlankLines, Is.False);

                                                                                         Odso odso = settings.Odso;
                                                                                         odso.DataSource = dataSrcFilename;
                                                                                         odso.DataSourceType = OdsoDataSourceType.Text;
                                                                                         odso.ColumnDelimiter = '|';
                                                                                         odso.FirstRowContainsColumnNames = true;

                                                                                         Assert.That(odso.Clone(), Is.Not.SameAs(odso));
                                                                                         Assert.That(settings.Clone(), Is.Not.SameAs(settings));

                                                                                         // Opening this document in Microsoft Word will execute the mail merge before displaying the contents. 
                                                                                         doc.Save(ArtifactsDir + "MailMerge.MailMergeSettings.docx");

Remarks

You can use this object to specify a mail merge data source for a document and this information (along with the available data fields) will appear in Microsoft Word when the user opens this document. Or you can use this object to query mail merge settings that the user has specified in Microsoft Word for this document.

This object is never null.

NodeType

Returns Aspose.Words.NodeType.Document.

public override NodeType NodeType { get; }

Property Value

NodeType

Examples

Shows how to traverse a composite node’s tree of child nodes.

public void RecurseChildren()
                                                                        {
                                                                            Document doc = new Document(MyDir + "Paragraphs.docx");

                                                                            // Any node that can contain child nodes, such as the document itself, is composite.
                                                                            Assert.That(doc.IsComposite, Is.True);

                                                                            // Invoke the recursive function that will go through and print all the child nodes of a composite node.
                                                                            TraverseAllNodes(doc, 0);
                                                                        }

                                                                        /// <summary>
                                                                        /// Recursively traverses a node tree while printing the type of each node
                                                                        /// with an indent depending on depth as well as the contents of all inline nodes.
                                                                        /// </summary>
                                                                        public void TraverseAllNodes(CompositeNode parentNode, int depth)
                                                                        {
                                                                            for (Node childNode = parentNode.FirstChild; childNode != null; childNode = childNode.NextSibling)
                                                                            {
                                                                                Console.Write($"{new string('\t', depth)}{Node.NodeTypeToString(childNode.NodeType)}");

                                                                                // Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
                                                                                if (childNode.IsComposite)
                                                                                {
                                                                                    Console.WriteLine();
                                                                                    TraverseAllNodes((CompositeNode)childNode, depth + 1);
                                                                                }
                                                                                else if (childNode is Inline)
                                                                                {
                                                                                    Console.WriteLine($" - \"{childNode.GetText().Trim()}\"");
                                                                                }
                                                                                else
                                                                                {
                                                                                    Console.WriteLine();
                                                                                }
                                                                            }
                                                                        }

OriginalFileName

Gets the original file name of the document.

public string OriginalFileName { get; }

Property Value

string

Examples

Shows how to retrieve details of a document’s load operation.

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

                                                                        Assert.That(doc.OriginalFileName, Is.EqualTo(MyDir + "Document.docx"));
                                                                        Assert.That(doc.OriginalLoadFormat, Is.EqualTo(LoadFormat.Docx));

Shows how to use the FileFormatUtil methods to detect the format of a document.

// Load a document from a file that is missing a file extension, and then detect its file format.
                                                                                          using (FileStream docStream = File.OpenRead(MyDir + "Word document with missing file extension"))
                                                                                          {
                                                                                              FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);
                                                                                              LoadFormat loadFormat = info.LoadFormat;

                                                                                              Assert.That(loadFormat, Is.EqualTo(LoadFormat.Doc));

                                                                                              // Below are two methods of converting a LoadFormat to its corresponding SaveFormat.
                                                                                              // 1 -  Get the file extension string for the LoadFormat, then get the corresponding SaveFormat from that string:
                                                                                              string fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
                                                                                              SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

                                                                                              // 2 -  Convert the LoadFormat directly to its SaveFormat:
                                                                                              saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

                                                                                              // Load a document from the stream, and then save it to the automatically detected file extension.
                                                                                              Document doc = new Document(docStream);

                                                                                              Assert.That(FileFormatUtil.SaveFormatToExtension(saveFormat), Is.EqualTo(".doc"));

                                                                                              doc.Save(ArtifactsDir + "File.SaveToDetectedFileFormat" + FileFormatUtil.SaveFormatToExtension(saveFormat));
                                                                                          }

Remarks

Returns null if the document was loaded from a stream or created blank.

OriginalLoadFormat

Gets the format of the original document that was loaded into this object.

public LoadFormat OriginalLoadFormat { get; }

Property Value

LoadFormat

Examples

Shows how to retrieve details of a document’s load operation.

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

                                                                        Assert.That(doc.OriginalFileName, Is.EqualTo(MyDir + "Document.docx"));
                                                                        Assert.That(doc.OriginalLoadFormat, Is.EqualTo(LoadFormat.Docx));

Remarks

If you created a new blank document, returns the Aspose.Words.LoadFormat.Doc value.

PackageCustomParts

Gets or sets the collection of custom parts (arbitrary content) that are linked to the OOXML package using “unknown relationships”.

public CustomPartCollection PackageCustomParts { get; set; }

Property Value

CustomPartCollection

Examples

Shows how to access a document’s arbitrary custom parts collection.

Document doc = new Document(MyDir + "Custom parts OOXML package.docx");

                                                                              Assert.That(doc.PackageCustomParts.Count, Is.EqualTo(2));

                                                                              // Clone the second part, then add the clone to the collection.
                                                                              CustomPart clonedPart = doc.PackageCustomParts[1].Clone();
                                                                              doc.PackageCustomParts.Add(clonedPart);
                                                                              Assert.That(doc.PackageCustomParts.Count, Is.EqualTo(3));

                                                                              // Enumerate over the collection and print every part.
                                                                              using (IEnumerator<CustomPart> enumerator = doc.PackageCustomParts.GetEnumerator())
                                                                              {
                                                                                  int index = 0;
                                                                                  while (enumerator.MoveNext())
                                                                                  {
                                                                                      Console.WriteLine($"Part index {index}:");
                                                                                      Console.WriteLine($"\tName:\t\t\t\t{enumerator.Current.Name}");
                                                                                      Console.WriteLine($"\tContent type:\t\t{enumerator.Current.ContentType}");
                                                                                      Console.WriteLine($"\tRelationship type:\t{enumerator.Current.RelationshipType}");
                                                                                      Console.WriteLine(enumerator.Current.IsExternal ?
                                                                                          "\tSourced from outside the document" :
                                                                                          $"\tStored within the document, length: {enumerator.Current.Data.Length} bytes");
                                                                                      index++;
                                                                                  }
                                                                              }

                                                                              // We can remove elements from this collection individually, or all at once.
                                                                              doc.PackageCustomParts.RemoveAt(2);

                                                                              Assert.That(doc.PackageCustomParts.Count, Is.EqualTo(2));

                                                                              doc.PackageCustomParts.Clear();

                                                                              Assert.That(doc.PackageCustomParts.Count, Is.EqualTo(0));

Remarks

Do not confuse these custom parts with Custom XML Data. If you need to access Custom XML parts, use the Aspose.Words.Document.CustomXmlParts property.

This collection contains OOXML parts whose parent is the OOXML package and they targets are of an "unknown relationship". For more information see Aspose.Words.Markup.CustomPart.

Aspose.Words loads and saves custom parts into OOXML documents only.

This property cannot be null.

Aspose.Words.Markup.CustomPart

PageCount

Gets the number of pages in the document as calculated by the most recent page layout operation.

public int PageCount { get; }

Property Value

int

Examples

Shows how to count the number of pages in the document.

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

                                                                  builder.Write("Page 1");
                                                                  builder.InsertBreak(BreakType.PageBreak);
                                                                  builder.Write("Page 2");
                                                                  builder.InsertBreak(BreakType.PageBreak);
                                                                  builder.Write("Page 3");

                                                                  // Verify the expected page count of the document.
                                                                  Assert.That(doc.PageCount, Is.EqualTo(3));

                                                                  // Getting the PageCount property invoked the document's page layout to calculate the value.
                                                                  // This operation will not need to be re-done when rendering the document to a fixed page save format,
                                                                  // such as .pdf. So you can save some time, especially with more complex documents.
                                                                  doc.Save(ArtifactsDir + "Document.GetPageCount.pdf");

See Also

Document . UpdatePageLayout ()

ProtectionType

Gets the currently active document protection type.

public ProtectionType ProtectionType { get; }

Property Value

ProtectionType

Examples

Shows how to protect and unprotect a document.

Document doc = new Document();
                                                         doc.Protect(ProtectionType.ReadOnly, "password");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         // If we open this document with Microsoft Word intending to edit it,
                                                         // we will need to apply the password to get through the protection.
                                                         doc.Save(ArtifactsDir + "Document.Protect.docx");

                                                         // Note that the protection only applies to Microsoft Word users opening our document.
                                                         // We have not encrypted the document in any way, and we do not need the password to open and edit it programmatically.
                                                         Document protectedDoc = new Document(ArtifactsDir + "Document.Protect.docx");

                                                         Assert.That(protectedDoc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         DocumentBuilder builder = new DocumentBuilder(protectedDoc);
                                                         builder.Writeln("Text added to a protected document.");
                                                         // There are two ways of removing protection from a document.
                                                         // 1 - With no password:
                                                         doc.Unprotect();

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.NoProtection));

                                                         doc.Protect(ProtectionType.ReadOnly, "NewPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         doc.Unprotect("WrongPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         // 2 - With the correct password:
                                                         doc.Unprotect("NewPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.NoProtection));

Remarks

This property allows to retrieve the currently set document protection type. To change the document protection type use the Aspose.Words.Document.Protect(Aspose.Words.ProtectionType,System.String) and Aspose.Words.Document.Unprotect methods.

When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

Note that document protection is different from write protection. Write protection is specified using the Aspose.Words.Document.WriteProtection

Aspose.Words.Document.Protect(Aspose.Words.ProtectionType,System.String) Aspose.Words.Document.Unprotect Aspose.Words.Document.WriteProtection

PunctuationKerning

Specifies whether kerning applies to both Latin text and punctuation.

public bool PunctuationKerning { get; set; }

Property Value

bool

Examples

Shows how to work with kerning applies to both Latin text and punctuation.

Document doc = new Document(MyDir + "Document.docx");
                                                                                     Assert.That(doc.PunctuationKerning, Is.True);

RemovePersonalInformation

Gets or sets a flag indicating that Microsoft Word will remove all user information from comments, revisions and document properties upon saving the document.

public bool RemovePersonalInformation { get; set; }

Property Value

bool

Examples

Shows how to enable the removal of personal information during a manual save.

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

                                                                                        // Insert some content with personal information.
                                                                                        doc.BuiltInDocumentProperties.Author = "John Doe";
                                                                                        doc.BuiltInDocumentProperties.Company = "Placeholder Inc.";

                                                                                        doc.StartTrackRevisions(doc.BuiltInDocumentProperties.Author, DateTime.Now);
                                                                                        builder.Write("Hello world!");
                                                                                        doc.StopTrackRevisions();

                                                                                        // This flag is equivalent to File -> Options -> Trust Center -> Trust Center Settings... ->
                                                                                        // Privacy Options -> "Remove personal information from file properties on save" in Microsoft Word.
                                                                                        doc.RemovePersonalInformation = saveWithoutPersonalInfo;

                                                                                        // This option will not take effect during a save operation made using Aspose.Words.
                                                                                        // Personal data will be removed from our document with the flag set when we save it manually using Microsoft Word.
                                                                                        doc.Save(ArtifactsDir + "Document.RemovePersonalInformation.docx");
                                                                                        doc = new Document(ArtifactsDir + "Document.RemovePersonalInformation.docx");

                                                                                        Assert.That(doc.RemovePersonalInformation, Is.EqualTo(saveWithoutPersonalInfo));
                                                                                        Assert.That(doc.BuiltInDocumentProperties.Author, Is.EqualTo("John Doe"));
                                                                                        Assert.That(doc.BuiltInDocumentProperties.Company, Is.EqualTo("Placeholder Inc."));
                                                                                        Assert.That(doc.Revisions[0].Author, Is.EqualTo("John Doe"));

Revisions

Gets a collection of revisions (tracked changes) that exist in this document.

public RevisionCollection Revisions { get; }

Property Value

RevisionCollection

Examples

Shows how to work with revisions in a document.

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

                                                          // Normal editing of the document does not count as a revision.
                                                          builder.Write("This does not count as a revision. ");

                                                          Assert.That(doc.HasRevisions, Is.False);

                                                          // To register our edits as revisions, we need to declare an author, and then start tracking them.
                                                          doc.StartTrackRevisions("John Doe", DateTime.Now);

                                                          builder.Write("This is revision #1. ");

                                                          Assert.That(doc.HasRevisions, Is.True);
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(1));

                                                          // This flag corresponds to the "Review" -> "Tracking" -> "Track Changes" option in Microsoft Word.
                                                          // The "StartTrackRevisions" method does not affect its value,
                                                          // and the document is tracking revisions programmatically despite it having a value of "false".
                                                          // If we open this document using Microsoft Word, it will not be tracking revisions.
                                                          Assert.That(doc.TrackRevisions, Is.False);

                                                          // We have added text using the document builder, so the first revision is an insertion-type revision.
                                                          Revision revision = doc.Revisions[0];
                                                          Assert.That(revision.Author, Is.EqualTo("John Doe"));
                                                          Assert.That(revision.ParentNode.GetText(), Is.EqualTo("This is revision #1. "));
                                                          Assert.That(revision.RevisionType, Is.EqualTo(RevisionType.Insertion));
                                                          Assert.That(DateTime.Now.Date, Is.EqualTo(revision.DateTime.Date));
                                                          Assert.That(revision.Group, Is.EqualTo(doc.Revisions.Groups[0]));

                                                          // Remove a run to create a deletion-type revision.
                                                          doc.FirstSection.Body.FirstParagraph.Runs[0].Remove();

                                                          // Adding a new revision places it at the beginning of the revision collection.
                                                          Assert.That(doc.Revisions[0].RevisionType, Is.EqualTo(RevisionType.Deletion));
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(2));

                                                          // Insert revisions show up in the document body even before we accept/reject the revision.
                                                          // Rejecting the revision will remove its nodes from the body. Conversely, nodes that make up delete revisions
                                                          // also linger in the document until we accept the revision.
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This does not count as a revision. This is revision #1."));

                                                          // Accepting the delete revision will remove its parent node from the paragraph text
                                                          // and then remove the collection's revision itself.
                                                          doc.Revisions[0].Accept();

                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #1."));

                                                          builder.Writeln("");
                                                          builder.Write("This is revision #2.");

                                                          // Now move the node to create a moving revision type.
                                                          Node node = doc.FirstSection.Body.Paragraphs[1];
                                                          Node endNode = doc.FirstSection.Body.Paragraphs[1].NextSibling;
                                                          Node referenceNode = doc.FirstSection.Body.Paragraphs[0];

                                                          while (node != endNode)
                                                          {
                                                              Node nextNode = node.NextSibling;
                                                              doc.FirstSection.Body.InsertBefore(node, referenceNode);
                                                              node = nextNode;
                                                          }

                                                          Assert.That(doc.Revisions[0].RevisionType, Is.EqualTo(RevisionType.Moving));
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(8));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #2.\rThis is revision #1. \rThis is revision #2."));

                                                          // The moving revision is now at index 1. Reject the revision to discard its contents.
                                                          doc.Revisions[1].Reject();

                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(6));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #1. \rThis is revision #2."));

Remarks

The returned collection is a "live" collection, which means if you remove parts of a document that contain revisions, the deleted revisions will automatically disappear from this collection.

RevisionsView

Gets or sets a value indicating whether to work with the original or revised version of a document.

public RevisionsView RevisionsView { get; set; }

Property Value

RevisionsView

Examples

Shows how to switch between the revised and the original view of a document.

Document doc = new Document(MyDir + "Revisions at list levels.docx");
                                                                                       doc.UpdateListLabels();

                                                                                       ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;
                                                                                       Assert.That(paragraphs[0].ListLabel.LabelString, Is.EqualTo("1."));
                                                                                       Assert.That(paragraphs[1].ListLabel.LabelString, Is.EqualTo("a."));
                                                                                       Assert.That(paragraphs[2].ListLabel.LabelString, Is.EqualTo(string.Empty));

                                                                                       // View the document object as if all the revisions are accepted. Currently supports list labels.
                                                                                       doc.RevisionsView = RevisionsView.Final;

                                                                                       Assert.That(paragraphs[0].ListLabel.LabelString, Is.EqualTo(string.Empty));
                                                                                       Assert.That(paragraphs[1].ListLabel.LabelString, Is.EqualTo("1."));
                                                                                       Assert.That(paragraphs[2].ListLabel.LabelString, Is.EqualTo("a."));

Remarks

The default value is Aspose.Words.RevisionsView.Original.

Sections

Returns a collection that represents all sections in the document.

public SectionCollection Sections { get; }

Property Value

SectionCollection

Examples

Shows how to add and remove sections in a document.

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

                                                              builder.Write("Section 1");
                                                              builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                              builder.Write("Section 2");

                                                              Assert.That(doc.GetText().Trim(), Is.EqualTo("Section 1\x000cSection 2"));

                                                              // Delete the first section from the document.
                                                              doc.Sections.RemoveAt(0);

                                                              Assert.That(doc.GetText().Trim(), Is.EqualTo("Section 2"));

                                                              // Append a copy of what is now the first section to the end of the document.
                                                              int lastSectionIdx = doc.Sections.Count - 1;
                                                              Section newSection = doc.Sections[lastSectionIdx].Clone();
                                                              doc.Sections.Add(newSection);

                                                              Assert.That(doc.GetText().Trim(), Is.EqualTo("Section 2\x000cSection 2"));

Shows how to specify how a new section separates itself from the previous.

Document doc = new Document();
                                                                                     DocumentBuilder builder = new DocumentBuilder(doc);
                                                                                     builder.Writeln("This text is in section 1.");

                                                                                     // Section break types determine how a new section separates itself from the previous section.
                                                                                     // Below are five types of section breaks.
                                                                                     // 1 -  Starts the next section on a new page:
                                                                                     builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                                                     builder.Writeln("This text is in section 2.");

                                                                                     Assert.That(doc.Sections[1].PageSetup.SectionStart, Is.EqualTo(SectionStart.NewPage));

                                                                                     // 2 -  Starts the next section on the current page:
                                                                                     builder.InsertBreak(BreakType.SectionBreakContinuous);
                                                                                     builder.Writeln("This text is in section 3.");

                                                                                     Assert.That(doc.Sections[2].PageSetup.SectionStart, Is.EqualTo(SectionStart.Continuous));

                                                                                     // 3 -  Starts the next section on a new even page:
                                                                                     builder.InsertBreak(BreakType.SectionBreakEvenPage);
                                                                                     builder.Writeln("This text is in section 4.");

                                                                                     Assert.That(doc.Sections[3].PageSetup.SectionStart, Is.EqualTo(SectionStart.EvenPage));

                                                                                     // 4 -  Starts the next section on a new odd page:
                                                                                     builder.InsertBreak(BreakType.SectionBreakOddPage);
                                                                                     builder.Writeln("This text is in section 5.");

                                                                                     Assert.That(doc.Sections[4].PageSetup.SectionStart, Is.EqualTo(SectionStart.OddPage));

                                                                                     // 5 -  Starts the next section on a new column:
                                                                                     TextColumnCollection columns = builder.PageSetup.TextColumns;
                                                                                     columns.SetCount(2);

                                                                                     builder.InsertBreak(BreakType.SectionBreakNewColumn);
                                                                                     builder.Writeln("This text is in section 6.");

                                                                                     Assert.That(doc.Sections[5].PageSetup.SectionStart, Is.EqualTo(SectionStart.NewColumn));

                                                                                     doc.Save(ArtifactsDir + "PageSetup.SetSectionStart.docx");

ShadeFormData

Specifies whether to turn on the gray shading on form fields.

public bool ShadeFormData { get; set; }

Property Value

bool

Examples

Shows how to apply gray shading to form fields.

Document doc = new Document();
                                                          DocumentBuilder builder = new DocumentBuilder(doc);
                                                          builder.Write("Hello world! ");
                                                          builder.InsertTextInput("My form field", TextFormFieldType.Regular, "",
                                                              "Text contents of form field, which are shaded in grey by default.", 0);

                                                          // We can turn the grey shading off, so the bookmarked text will blend in with the other text.
                                                          doc.ShadeFormData = useGreyShading;
                                                          doc.Save(ArtifactsDir + "Document.ShadeFormData.docx");

ShowGrammaticalErrors

Specifies whether to display grammar errors in this document.

public bool ShowGrammaticalErrors { get; set; }

Property Value

bool

Examples

Shows how to show/hide errors in the document.

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

                                                         // Insert two sentences with mistakes that would be picked up
                                                         // by the spelling and grammar checkers in Microsoft Word.
                                                         builder.Writeln("There is a speling error in this sentence.");
                                                         builder.Writeln("Their is a grammatical error in this sentence.");

                                                         // If these options are enabled, then spelling errors will be underlined
                                                         // in the output document by a jagged red line, and a double blue line will highlight grammatical mistakes.
                                                         doc.ShowGrammaticalErrors = showErrors;
                                                         doc.ShowSpellingErrors = showErrors;

                                                         doc.Save(ArtifactsDir + "Document.SpellingAndGrammarErrors.docx");

ShowSpellingErrors

Specifies whether to display spelling errors in this document.

public bool ShowSpellingErrors { get; set; }

Property Value

bool

Examples

Shows how to show/hide errors in the document.

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

                                                         // Insert two sentences with mistakes that would be picked up
                                                         // by the spelling and grammar checkers in Microsoft Word.
                                                         builder.Writeln("There is a speling error in this sentence.");
                                                         builder.Writeln("Their is a grammatical error in this sentence.");

                                                         // If these options are enabled, then spelling errors will be underlined
                                                         // in the output document by a jagged red line, and a double blue line will highlight grammatical mistakes.
                                                         doc.ShowGrammaticalErrors = showErrors;
                                                         doc.ShowSpellingErrors = showErrors;

                                                         doc.Save(ArtifactsDir + "Document.SpellingAndGrammarErrors.docx");

SpellingChecked

Returns true if the document has been checked for spelling.

public bool SpellingChecked { get; set; }

Property Value

bool

Examples

Shows how to set spelling or grammar verifying.

Document doc = new Document();

                                                          // The string with spelling errors.
                                                          doc.FirstSection.Body.FirstParagraph.Runs.Add(new Run(doc, "The speeling in this documentz is all broked."));

                                                          // Spelling/Grammar check start if we set properties to false.
                                                          // We can see all errors in Microsoft Word via Review -> Spelling & Grammar.
                                                          // Note that Microsoft Word does not start grammar/spell check automatically for DOC and RTF document format.
                                                          doc.SpellingChecked = checkSpellingGrammar;
                                                          doc.GrammarChecked = checkSpellingGrammar;

                                                          doc.Save(ArtifactsDir + "Document.SpellingOrGrammar.docx");

Remarks

To recheck the spelling in the document, set this property to false.

Theme

Gets the Aspose.Words.Document.Theme object for this document.

public Theme Theme { get; }

Property Value

Theme

Examples

Shows how to set custom colors and fonts for themes.

Document doc = new Document(MyDir + "Theme colors.docx");

                                                               // The "Theme" object gives us access to the document theme, a source of default fonts and colors.
                                                               Theme theme = doc.Theme;

                                                               // Some styles, such as "Heading 1" and "Subtitle", will inherit these fonts.
                                                               theme.MajorFonts.Latin = "Courier New";
                                                               theme.MinorFonts.Latin = "Agency FB";

                                                               // Other languages may also have their custom fonts in this theme.
                                                               Assert.That(theme.MajorFonts.ComplexScript, Is.EqualTo(string.Empty));
                                                               Assert.That(theme.MajorFonts.EastAsian, Is.EqualTo(string.Empty));
                                                               Assert.That(theme.MinorFonts.ComplexScript, Is.EqualTo(string.Empty));
                                                               Assert.That(theme.MinorFonts.EastAsian, Is.EqualTo(string.Empty));

                                                               // The "Colors" property contains the color palette from Microsoft Word,
                                                               // which appears when changing shading or font color.
                                                               // Apply custom colors to the color palette so we have easy access to them in Microsoft Word
                                                               // when we, for example, change the font color via "Home" -> "Font" -> "Font Color",
                                                               // or insert a shape, and then set a color for it via "Shape Format" -> "Shape Styles".
                                                               ThemeColors colors = theme.Colors;
                                                               colors.Dark1 = Color.MidnightBlue;
                                                               colors.Light1 = Color.PaleGreen;
                                                               colors.Dark2 = Color.Indigo;
                                                               colors.Light2 = Color.Khaki;

                                                               colors.Accent1 = Color.OrangeRed;
                                                               colors.Accent2 = Color.LightSalmon;
                                                               colors.Accent3 = Color.Yellow;
                                                               colors.Accent4 = Color.Gold;
                                                               colors.Accent5 = Color.BlueViolet;
                                                               colors.Accent6 = Color.DarkViolet;

                                                               // Apply custom colors to hyperlinks in their clicked and un-clicked states.
                                                               colors.Hyperlink = Color.Black;
                                                               colors.FollowedHyperlink = Color.Gray;

                                                               doc.Save(ArtifactsDir + "Themes.CustomColorsAndFonts.docx");

TrackRevisions

True if changes are tracked when this document is edited in Microsoft Word.

public bool TrackRevisions { get; set; }

Property Value

bool

Examples

Shows how to work with revisions in a document.

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

                                                          // Normal editing of the document does not count as a revision.
                                                          builder.Write("This does not count as a revision. ");

                                                          Assert.That(doc.HasRevisions, Is.False);

                                                          // To register our edits as revisions, we need to declare an author, and then start tracking them.
                                                          doc.StartTrackRevisions("John Doe", DateTime.Now);

                                                          builder.Write("This is revision #1. ");

                                                          Assert.That(doc.HasRevisions, Is.True);
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(1));

                                                          // This flag corresponds to the "Review" -> "Tracking" -> "Track Changes" option in Microsoft Word.
                                                          // The "StartTrackRevisions" method does not affect its value,
                                                          // and the document is tracking revisions programmatically despite it having a value of "false".
                                                          // If we open this document using Microsoft Word, it will not be tracking revisions.
                                                          Assert.That(doc.TrackRevisions, Is.False);

                                                          // We have added text using the document builder, so the first revision is an insertion-type revision.
                                                          Revision revision = doc.Revisions[0];
                                                          Assert.That(revision.Author, Is.EqualTo("John Doe"));
                                                          Assert.That(revision.ParentNode.GetText(), Is.EqualTo("This is revision #1. "));
                                                          Assert.That(revision.RevisionType, Is.EqualTo(RevisionType.Insertion));
                                                          Assert.That(DateTime.Now.Date, Is.EqualTo(revision.DateTime.Date));
                                                          Assert.That(revision.Group, Is.EqualTo(doc.Revisions.Groups[0]));

                                                          // Remove a run to create a deletion-type revision.
                                                          doc.FirstSection.Body.FirstParagraph.Runs[0].Remove();

                                                          // Adding a new revision places it at the beginning of the revision collection.
                                                          Assert.That(doc.Revisions[0].RevisionType, Is.EqualTo(RevisionType.Deletion));
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(2));

                                                          // Insert revisions show up in the document body even before we accept/reject the revision.
                                                          // Rejecting the revision will remove its nodes from the body. Conversely, nodes that make up delete revisions
                                                          // also linger in the document until we accept the revision.
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This does not count as a revision. This is revision #1."));

                                                          // Accepting the delete revision will remove its parent node from the paragraph text
                                                          // and then remove the collection's revision itself.
                                                          doc.Revisions[0].Accept();

                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #1."));

                                                          builder.Writeln("");
                                                          builder.Write("This is revision #2.");

                                                          // Now move the node to create a moving revision type.
                                                          Node node = doc.FirstSection.Body.Paragraphs[1];
                                                          Node endNode = doc.FirstSection.Body.Paragraphs[1].NextSibling;
                                                          Node referenceNode = doc.FirstSection.Body.Paragraphs[0];

                                                          while (node != endNode)
                                                          {
                                                              Node nextNode = node.NextSibling;
                                                              doc.FirstSection.Body.InsertBefore(node, referenceNode);
                                                              node = nextNode;
                                                          }

                                                          Assert.That(doc.Revisions[0].RevisionType, Is.EqualTo(RevisionType.Moving));
                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(8));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #2.\rThis is revision #1. \rThis is revision #2."));

                                                          // The moving revision is now at index 1. Reject the revision to discard its contents.
                                                          doc.Revisions[1].Reject();

                                                          Assert.That(doc.Revisions.Count, Is.EqualTo(6));
                                                          Assert.That(doc.GetText().Trim(), Is.EqualTo("This is revision #1. \rThis is revision #2."));

Remarks

Setting this option only instructs Microsoft Word whether the track changes is turned on or off. This property has no effect on changes to the document that you make programmatically via Aspose.Words.

If you want to automatically track changes as they are made programmatically by Aspose.Words to this document use the Aspose.Words.Document.StartTrackRevisions(System.String,System.DateTime) method.

Variables

Returns the collection of variables added to a document or template.

public VariableCollection Variables { get; }

Property Value

VariableCollection

Examples

Shows how to work with a document’s variable collection.

Document doc = new Document();
                                                                   VariableCollection variables = doc.Variables;

                                                                   // Every document has a collection of key/value pair variables, which we can add items to.
                                                                   variables.Add("Home address", "123 Main St.");
                                                                   variables.Add("City", "London");
                                                                   variables.Add("Bedrooms", "3");

                                                                   Assert.That(variables.Count, Is.EqualTo(3));

                                                                   // We can display the values of variables in the document body using DOCVARIABLE fields.
                                                                   DocumentBuilder builder = new DocumentBuilder(doc);
                                                                   FieldDocVariable field = (FieldDocVariable)builder.InsertField(FieldType.FieldDocVariable, true);
                                                                   field.VariableName = "Home address";
                                                                   field.Update();

                                                                   Assert.That(field.Result, Is.EqualTo("123 Main St."));

                                                                   // Assigning values to existing keys will update them.
                                                                   variables.Add("Home address", "456 Queen St.");

                                                                   // We will then have to update DOCVARIABLE fields to ensure they display an up-to-date value.
                                                                   Assert.That(field.Result, Is.EqualTo("123 Main St."));

                                                                   field.Update();

                                                                   Assert.That(field.Result, Is.EqualTo("456 Queen St."));

                                                                   // Verify that the document variables with a certain name or value exist.
                                                                   Assert.That(variables.Contains("City"), Is.True);
                                                                   Assert.That(variables.Any(v => v.Value == "London"), Is.True);

                                                                   // The collection of variables automatically sorts variables alphabetically by name.
                                                                   Assert.That(variables.IndexOfKey("Bedrooms"), Is.EqualTo(0));
                                                                   Assert.That(variables.IndexOfKey("City"), Is.EqualTo(1));
                                                                   Assert.That(variables.IndexOfKey("Home address"), Is.EqualTo(2));

                                                                   Assert.That(variables[0], Is.EqualTo("3"));
                                                                   Assert.That(variables["City"], Is.EqualTo("London"));

                                                                   // Enumerate over the collection of variables.
                                                                   using (IEnumerator<KeyValuePair<string, string>> enumerator = doc.Variables.GetEnumerator())
                                                                       while (enumerator.MoveNext())
                                                                           Console.WriteLine($"Name: {enumerator.Current.Key}, Value: {enumerator.Current.Value}");

                                                                   // Below are three ways of removing document variables from a collection.
                                                                   // 1 -  By name:
                                                                   variables.Remove("City");

                                                                   Assert.That(variables.Contains("City"), Is.False);

                                                                   // 2 -  By index:
                                                                   variables.RemoveAt(1);

                                                                   Assert.That(variables.Contains("Home address"), Is.False);

                                                                   // 3 -  Clear the whole collection at once:
                                                                   variables.Clear();

                                                                   Assert.That(variables.Count, Is.EqualTo(0));

VbaProject

Gets or sets a Aspose.Words.Document.VbaProject.

public VbaProject VbaProject { get; set; }

Property Value

VbaProject

Examples

Shows how to access a document’s VBA project information.

Document doc = new Document(MyDir + "VBA project.docm");

                                                                    // A VBA project contains a collection of VBA modules.
                                                                    VbaProject vbaProject = doc.VbaProject;
                                                                    Console.WriteLine(vbaProject.IsSigned
                                                                        ? $"Project name: {vbaProject.Name} signed; Project code page: {vbaProject.CodePage}; Modules count: {vbaProject.Modules.Count()}\n"
                                                                        : $"Project name: {vbaProject.Name} not signed; Project code page: {vbaProject.CodePage}; Modules count: {vbaProject.Modules.Count()}\n");

                                                                    VbaModuleCollection vbaModules = doc.VbaProject.Modules;

                                                                    Assert.That(3, Is.EqualTo(vbaModules.Count()));

                                                                    foreach (VbaModule module in vbaModules)
                                                                        Console.WriteLine($"Module name: {module.Name};\nModule code:\n{module.SourceCode}\n");

                                                                    // Set new source code for VBA module. You can access VBA modules in the collection either by index or by name.
                                                                    vbaModules[0].SourceCode = "Your VBA code...";
                                                                    vbaModules["Module1"].SourceCode = "Your VBA code...";

                                                                    // Remove a module from the collection.
                                                                    vbaModules.Remove(vbaModules[2]);

VersionsCount

Gets the number of document versions that was stored in the DOC document.

public int VersionsCount { get; }

Property Value

int

Examples

Shows how to work with the versions count feature of older Microsoft Word documents.

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

                                                                                               // We can read this property of a document, but we cannot preserve it while saving.
                                                                                               Assert.That(doc.VersionsCount, Is.EqualTo(4));

                                                                                               doc.Save(ArtifactsDir + "Document.VersionsCount.doc");
                                                                                               doc = new Document(ArtifactsDir + "Document.VersionsCount.doc");

                                                                                               Assert.That(doc.VersionsCount, Is.EqualTo(0));

Remarks

Versions in Microsoft Word are accessed via the File/Versions menu. Microsoft Word supports versions only for DOC files.

This property allows to detect if there were document versions stored in this document before it was opened in Aspose.Words. Aspose.Words provides no other support for document versions. If you save this document using Aspose.Words, the document will be saved without versions.

ViewOptions

Provides options to control how the document is displayed in Microsoft Word.

public ViewOptions ViewOptions { get; }

Property Value

ViewOptions

Examples

Shows how to set a custom zoom factor, which older versions of Microsoft Word will apply to a document upon loading.

Document doc = new Document();
                                                                                                                               DocumentBuilder builder = new DocumentBuilder(doc);
                                                                                                                               builder.Writeln("Hello world!");

                                                                                                                               doc.ViewOptions.ViewType = ViewType.PageLayout;
                                                                                                                               doc.ViewOptions.ZoomPercent = 50;

                                                                                                                               Assert.That(doc.ViewOptions.ZoomType, Is.EqualTo(ZoomType.Custom));
                                                                                                                               Assert.That(doc.ViewOptions.ZoomType, Is.EqualTo(ZoomType.None));

                                                                                                                               doc.Save(ArtifactsDir + "ViewOptions.SetZoomPercentage.doc");

Shows how to set a custom zoom type, which older versions of Microsoft Word will apply to a document upon loading.

Document doc = new Document();
                                                                                                                             DocumentBuilder builder = new DocumentBuilder(doc);
                                                                                                                             builder.Writeln("Hello world!");

                                                                                                                             // Set the "ZoomType" property to "ZoomType.PageWidth" to get Microsoft Word
                                                                                                                             // to automatically zoom the document to fit the width of the page.
                                                                                                                             // Set the "ZoomType" property to "ZoomType.FullPage" to get Microsoft Word
                                                                                                                             // to automatically zoom the document to make the entire first page visible.
                                                                                                                             // Set the "ZoomType" property to "ZoomType.TextFit" to get Microsoft Word
                                                                                                                             // to automatically zoom the document to fit the inner text margins of the first page.
                                                                                                                             doc.ViewOptions.ZoomType = zoomType;

                                                                                                                             doc.Save(ArtifactsDir + "ViewOptions.SetZoomType.doc");

Watermark

Provides access to the document watermark.

public Watermark Watermark { get; }

Property Value

Watermark

Examples

Shows how to create a text watermark.

Document doc = new Document();

                                                // Add a plain text watermark.
                                                doc.Watermark.SetText("Aspose Watermark");

                                                // If we wish to edit the text formatting using it as a watermark,
                                                // we can do so by passing a TextWatermarkOptions object when creating the watermark.
                                                TextWatermarkOptions textWatermarkOptions = new TextWatermarkOptions();
                                                textWatermarkOptions.FontFamily = "Arial";
                                                textWatermarkOptions.FontSize = 36;
                                                textWatermarkOptions.Color = Color.Black;
                                                textWatermarkOptions.Layout = WatermarkLayout.Diagonal;
                                                textWatermarkOptions.IsSemitrasparent = false;

                                                doc.Watermark.SetText("Aspose Watermark", textWatermarkOptions);

                                                doc.Save(ArtifactsDir + "Document.TextWatermark.docx");

                                                // We can remove a watermark from a document like this.
                                                if (doc.Watermark.Type == WatermarkType.Text)
                                                    doc.Watermark.Remove();

WebExtensionTaskPanes

Returns a collection that represents a list of task pane add-ins.

public TaskPaneCollection WebExtensionTaskPanes { get; }

Property Value

TaskPaneCollection

Examples

Shows how to add a web extension to a document.

Document doc = new Document();

                                                          // Create task pane with "MyScript" add-in, which will be used by the document,
                                                          // then set its default location.
                                                          TaskPane myScriptTaskPane = new TaskPane();
                                                          doc.WebExtensionTaskPanes.Add(myScriptTaskPane);
                                                          myScriptTaskPane.DockState = TaskPaneDockState.Right;
                                                          myScriptTaskPane.IsVisible = true;
                                                          myScriptTaskPane.Width = 300;
                                                          myScriptTaskPane.IsLocked = true;

                                                          // If there are multiple task panes in the same docking location, we can set this index to arrange them.
                                                          myScriptTaskPane.Row = 1;

                                                          // Create an add-in called "MyScript Math Sample", which the task pane will display within.
                                                          WebExtension webExtension = myScriptTaskPane.WebExtension;

                                                          // Set application store reference parameters for our add-in, such as the ID.
                                                          webExtension.Reference.Id = "WA104380646";
                                                          webExtension.Reference.Version = "1.0.0.0";
                                                          webExtension.Reference.StoreType = WebExtensionStoreType.OMEX;
                                                          webExtension.Reference.Store = CultureInfo.CurrentCulture.Name;
                                                          webExtension.Properties.Add(new WebExtensionProperty("MyScript", "MyScript Math Sample"));
                                                          webExtension.Bindings.Add(new WebExtensionBinding("MyScript", WebExtensionBindingType.Text, "104380646"));

                                                          // Allow the user to interact with the add-in.
                                                          webExtension.IsFrozen = false;

                                                          // We can access the web extension in Microsoft Word via Developer -> Add-ins.
                                                          doc.Save(ArtifactsDir + "Document.WebExtension.docx");

                                                          // Remove all web extension task panes at once like this.
                                                          doc.WebExtensionTaskPanes.Clear();

                                                          Assert.That(doc.WebExtensionTaskPanes.Count, Is.EqualTo(0));

                                                          doc = new Document(ArtifactsDir + "Document.WebExtension.docx");

                                                          myScriptTaskPane = doc.WebExtensionTaskPanes[0];
                                                          Assert.That(myScriptTaskPane.DockState, Is.EqualTo(TaskPaneDockState.Right));
                                                          Assert.That(myScriptTaskPane.IsVisible, Is.True);
                                                          Assert.That(myScriptTaskPane.Width, Is.EqualTo(300.0d));
                                                          Assert.That(myScriptTaskPane.IsLocked, Is.True);
                                                          Assert.That(myScriptTaskPane.Row, Is.EqualTo(1));

                                                          webExtension = myScriptTaskPane.WebExtension;
                                                          Assert.That(webExtension.Id, Is.EqualTo(string.Empty));

                                                          Assert.That(webExtension.Reference.Id, Is.EqualTo("WA104380646"));
                                                          Assert.That(webExtension.Reference.Version, Is.EqualTo("1.0.0.0"));
                                                          Assert.That(webExtension.Reference.StoreType, Is.EqualTo(WebExtensionStoreType.OMEX));
                                                          Assert.That(webExtension.Reference.Store, Is.EqualTo(CultureInfo.CurrentCulture.Name));
                                                          Assert.That(webExtension.AlternateReferences.Count, Is.EqualTo(0));

                                                          Assert.That(webExtension.Properties[0].Name, Is.EqualTo("MyScript"));
                                                          Assert.That(webExtension.Properties[0].Value, Is.EqualTo("MyScript Math Sample"));

                                                          Assert.That(webExtension.Bindings[0].Id, Is.EqualTo("MyScript"));
                                                          Assert.That(webExtension.Bindings[0].BindingType, Is.EqualTo(WebExtensionBindingType.Text));
                                                          Assert.That(webExtension.Bindings[0].AppRef, Is.EqualTo("104380646"));

                                                          Assert.That(webExtension.IsFrozen, Is.False);

WriteProtection

Provides access to the document write protection options.

public WriteProtection WriteProtection { get; }

Property Value

WriteProtection

Examples

Shows how to protect a document with a password.

Document doc = new Document();
                                                           DocumentBuilder builder = new DocumentBuilder(doc);
                                                           builder.Writeln("Hello world! This document is protected.");
                                                           // Enter a password up to 15 characters in length, and then verify the document's protection status.
                                                           doc.WriteProtection.SetPassword("MyPassword");
                                                           doc.WriteProtection.ReadOnlyRecommended = true;

                                                           Assert.That(doc.WriteProtection.IsWriteProtected, Is.True);
                                                           Assert.That(doc.WriteProtection.ValidatePassword("MyPassword"), Is.True);

                                                           // Protection does not prevent the document from being edited programmatically, nor does it encrypt the contents.
                                                           doc.Save(ArtifactsDir + "Document.WriteProtection.docx");
                                                           doc = new Document(ArtifactsDir + "Document.WriteProtection.docx");

                                                           Assert.That(doc.WriteProtection.IsWriteProtected, Is.True);

                                                           builder = new DocumentBuilder(doc);
                                                           builder.MoveToDocumentEnd();
                                                           builder.Writeln("Writing text in a protected document.");

                                                           Assert.That(doc.GetText().Trim(), Is.EqualTo("Hello world! This document is protected." +
                                                                           "\rWriting text in a protected document."));

Methods

Accept(DocumentVisitor)

Accepts a visitor.

public override bool Accept(DocumentVisitor visitor)

Parameters

visitor DocumentVisitor

The visitor that will visit the nodes.

Returns

bool

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

Examples

Shows how to use a document visitor to print a document’s node structure.

public void DocStructureToText()
                                                                                    {
                                                                                        Document doc = new Document(MyDir + "DocumentVisitor-compatible features.docx");
                                                                                        DocStructurePrinter visitor = new DocStructurePrinter();

                                                                                        // When we get a composite node to accept a document visitor, the visitor visits the accepting node,
                                                                                        // and then traverses all the node's children in a depth-first manner.
                                                                                        // The visitor can read and modify each visited node.
                                                                                        doc.Accept(visitor);

                                                                                        Console.WriteLine(visitor.GetText());
                                                                                    }

                                                                                    /// <summary>
                                                                                    /// Traverses a node's tree of child nodes.
                                                                                    /// Creates a map of this tree in the form of a string.
                                                                                    /// </summary>
                                                                                    public class DocStructurePrinter : DocumentVisitor
                                                                                    {
                                                                                        public DocStructurePrinter()
                                                                                        {
                                                                                            mAcceptingNodeChildTree = new StringBuilder();
                                                                                        }

                                                                                        public string GetText()
                                                                                        {
                                                                                            return mAcceptingNodeChildTree.ToString();
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Document node is encountered.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitDocumentStart(Document doc)
                                                                                        {
                                                                                            int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

                                                                                            IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
                                                                                            mDocTraversalDepth++;

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

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Document node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitDocumentEnd(Document doc)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Document end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Section node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSectionStart(Section section)
                                                                                        {
                                                                                            // Get the index of our section within the document.
                                                                                            NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
                                                                                            int sectionIndex = docSections.IndexOf(section);

                                                                                            IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Section node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSectionEnd(Section section)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Section end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Body node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitBodyStart(Body body)
                                                                                        {
                                                                                            int paragraphCount = body.Paragraphs.Count;
                                                                                            IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Body node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitBodyEnd(Body body)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Body end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Paragraph node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitParagraphStart(Paragraph paragraph)
                                                                                        {
                                                                                            IndentAndAppendLine("[Paragraph start]");
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Paragraph node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Paragraph end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Run node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitRun(Run run)
                                                                                        {
                                                                                            IndentAndAppendLine("[Run] \"" + run.GetText() + "\"");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSubDocument(SubDocument subDocument)
                                                                                        {
                                                                                            IndentAndAppendLine("[SubDocument]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart)
                                                                                        {
                                                                                            IndentAndAppendLine("[SdtRangeStart]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd)
                                                                                        {
                                                                                            IndentAndAppendLine("[SdtRangeEnd]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
                                                                                        /// </summary>
                                                                                        /// <param name="text"></param>
                                                                                        private void IndentAndAppendLine(string text)
                                                                                        {
                                                                                            for (int i = 0; i < mDocTraversalDepth; i++) mAcceptingNodeChildTree.Append("|  ");

                                                                                            mAcceptingNodeChildTree.AppendLine(text);
                                                                                        }

                                                                                        private int mDocTraversalDepth;
                                                                                        private readonly StringBuilder mAcceptingNodeChildTree;
                                                                                    }

Remarks

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

For more info see the Visitor design pattern.

AcceptAllRevisions()

Accepts all tracked changes in the document.

public void AcceptAllRevisions()

Examples

Shows how to accept all tracking changes in the document.

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

                                                                    // Edit the document while tracking changes to create a few revisions.
                                                                    doc.StartTrackRevisions("John Doe");
                                                                    builder.Write("Hello world! ");
                                                                    builder.Write("Hello again! ");
                                                                    builder.Write("This is another revision.");
                                                                    doc.StopTrackRevisions();

                                                                    Assert.That(doc.Revisions.Count, Is.EqualTo(3));

                                                                    // We can iterate through every revision and accept/reject it as a part of our document.
                                                                    // If we know we wish to accept every revision, we can do it more straightforwardly so by calling this method.
                                                                    doc.AcceptAllRevisions();

                                                                    Assert.That(doc.Revisions.Count, Is.EqualTo(0));
                                                                    Assert.That(doc.GetText().Trim(), Is.EqualTo("Hello world! Hello again! This is another revision."));

Remarks

This method is a shortcut for Aspose.Words.RevisionCollection.AcceptAll.

AcceptEnd(DocumentVisitor)

Accepts a visitor for visiting the end of the document.

public override VisitorAction AcceptEnd(DocumentVisitor visitor)

Parameters

visitor DocumentVisitor

The document visitor.

Returns

VisitorAction

The action to be taken by the visitor.

Examples

Shows how to use a document visitor to print a document’s node structure.

public void DocStructureToText()
                                                                                    {
                                                                                        Document doc = new Document(MyDir + "DocumentVisitor-compatible features.docx");
                                                                                        DocStructurePrinter visitor = new DocStructurePrinter();

                                                                                        // When we get a composite node to accept a document visitor, the visitor visits the accepting node,
                                                                                        // and then traverses all the node's children in a depth-first manner.
                                                                                        // The visitor can read and modify each visited node.
                                                                                        doc.Accept(visitor);

                                                                                        Console.WriteLine(visitor.GetText());
                                                                                    }

                                                                                    /// <summary>
                                                                                    /// Traverses a node's tree of child nodes.
                                                                                    /// Creates a map of this tree in the form of a string.
                                                                                    /// </summary>
                                                                                    public class DocStructurePrinter : DocumentVisitor
                                                                                    {
                                                                                        public DocStructurePrinter()
                                                                                        {
                                                                                            mAcceptingNodeChildTree = new StringBuilder();
                                                                                        }

                                                                                        public string GetText()
                                                                                        {
                                                                                            return mAcceptingNodeChildTree.ToString();
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Document node is encountered.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitDocumentStart(Document doc)
                                                                                        {
                                                                                            int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

                                                                                            IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
                                                                                            mDocTraversalDepth++;

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

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Document node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitDocumentEnd(Document doc)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Document end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Section node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSectionStart(Section section)
                                                                                        {
                                                                                            // Get the index of our section within the document.
                                                                                            NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
                                                                                            int sectionIndex = docSections.IndexOf(section);

                                                                                            IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Section node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSectionEnd(Section section)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Section end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Body node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitBodyStart(Body body)
                                                                                        {
                                                                                            int paragraphCount = body.Paragraphs.Count;
                                                                                            IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Body node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitBodyEnd(Body body)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Body end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Paragraph node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitParagraphStart(Paragraph paragraph)
                                                                                        {
                                                                                            IndentAndAppendLine("[Paragraph start]");
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Paragraph node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Paragraph end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Run node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitRun(Run run)
                                                                                        {
                                                                                            IndentAndAppendLine("[Run] \"" + run.GetText() + "\"");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSubDocument(SubDocument subDocument)
                                                                                        {
                                                                                            IndentAndAppendLine("[SubDocument]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart)
                                                                                        {
                                                                                            IndentAndAppendLine("[SdtRangeStart]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd)
                                                                                        {
                                                                                            IndentAndAppendLine("[SdtRangeEnd]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
                                                                                        /// </summary>
                                                                                        /// <param name="text"></param>
                                                                                        private void IndentAndAppendLine(string text)
                                                                                        {
                                                                                            for (int i = 0; i < mDocTraversalDepth; i++) mAcceptingNodeChildTree.Append("|  ");

                                                                                            mAcceptingNodeChildTree.AppendLine(text);
                                                                                        }

                                                                                        private int mDocTraversalDepth;
                                                                                        private readonly StringBuilder mAcceptingNodeChildTree;
                                                                                    }

AcceptStart(DocumentVisitor)

Accepts a visitor for visiting the start of the document.

public override VisitorAction AcceptStart(DocumentVisitor visitor)

Parameters

visitor DocumentVisitor

The document visitor.

Returns

VisitorAction

The action to be taken by the visitor.

Examples

Shows how to use a document visitor to print a document’s node structure.

public void DocStructureToText()
                                                                                    {
                                                                                        Document doc = new Document(MyDir + "DocumentVisitor-compatible features.docx");
                                                                                        DocStructurePrinter visitor = new DocStructurePrinter();

                                                                                        // When we get a composite node to accept a document visitor, the visitor visits the accepting node,
                                                                                        // and then traverses all the node's children in a depth-first manner.
                                                                                        // The visitor can read and modify each visited node.
                                                                                        doc.Accept(visitor);

                                                                                        Console.WriteLine(visitor.GetText());
                                                                                    }

                                                                                    /// <summary>
                                                                                    /// Traverses a node's tree of child nodes.
                                                                                    /// Creates a map of this tree in the form of a string.
                                                                                    /// </summary>
                                                                                    public class DocStructurePrinter : DocumentVisitor
                                                                                    {
                                                                                        public DocStructurePrinter()
                                                                                        {
                                                                                            mAcceptingNodeChildTree = new StringBuilder();
                                                                                        }

                                                                                        public string GetText()
                                                                                        {
                                                                                            return mAcceptingNodeChildTree.ToString();
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Document node is encountered.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitDocumentStart(Document doc)
                                                                                        {
                                                                                            int childNodeCount = doc.GetChildNodes(NodeType.Any, true).Count;

                                                                                            IndentAndAppendLine("[Document start] Child nodes: " + childNodeCount);
                                                                                            mDocTraversalDepth++;

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

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Document node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitDocumentEnd(Document doc)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Document end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Section node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSectionStart(Section section)
                                                                                        {
                                                                                            // Get the index of our section within the document.
                                                                                            NodeCollection docSections = section.Document.GetChildNodes(NodeType.Section, false);
                                                                                            int sectionIndex = docSections.IndexOf(section);

                                                                                            IndentAndAppendLine("[Section start] Section index: " + sectionIndex);
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Section node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSectionEnd(Section section)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Section end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Body node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitBodyStart(Body body)
                                                                                        {
                                                                                            int paragraphCount = body.Paragraphs.Count;
                                                                                            IndentAndAppendLine("[Body start] Paragraphs: " + paragraphCount);
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Body node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitBodyEnd(Body body)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Body end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Paragraph node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitParagraphStart(Paragraph paragraph)
                                                                                        {
                                                                                            IndentAndAppendLine("[Paragraph start]");
                                                                                            mDocTraversalDepth++;

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called after all the child nodes of a Paragraph node have been visited.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
                                                                                        {
                                                                                            mDocTraversalDepth--;
                                                                                            IndentAndAppendLine("[Paragraph end]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a Run node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitRun(Run run)
                                                                                        {
                                                                                            IndentAndAppendLine("[Run] \"" + run.GetText() + "\"");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitSubDocument(SubDocument subDocument)
                                                                                        {
                                                                                            IndentAndAppendLine("[SubDocument]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitStructuredDocumentTagRangeStart(StructuredDocumentTagRangeStart sdtRangeStart)
                                                                                        {
                                                                                            IndentAndAppendLine("[SdtRangeStart]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Called when a SubDocument node is encountered in the document.
                                                                                        /// </summary>
                                                                                        public override VisitorAction VisitStructuredDocumentTagRangeEnd(StructuredDocumentTagRangeEnd sdtRangeEnd)
                                                                                        {
                                                                                            IndentAndAppendLine("[SdtRangeEnd]");

                                                                                            return VisitorAction.Continue;
                                                                                        }

                                                                                        /// <summary>
                                                                                        /// Append a line to the StringBuilder and indent it depending on how deep the visitor is into the document tree.
                                                                                        /// </summary>
                                                                                        /// <param name="text"></param>
                                                                                        private void IndentAndAppendLine(string text)
                                                                                        {
                                                                                            for (int i = 0; i < mDocTraversalDepth; i++) mAcceptingNodeChildTree.Append("|  ");

                                                                                            mAcceptingNodeChildTree.AppendLine(text);
                                                                                        }

                                                                                        private int mDocTraversalDepth;
                                                                                        private readonly StringBuilder mAcceptingNodeChildTree;
                                                                                    }

AppendDocument(Document, ImportFormatMode)

Appends the specified document to the end of this document.

public void AppendDocument(Document srcDoc, ImportFormatMode importFormatMode)

Parameters

srcDoc Document

The document to append.

importFormatMode ImportFormatMode

Specifies how to merge style formatting that clashes.

Examples

Shows how to append a document to the end of another document.

Document srcDoc = new Document();
                                                                         srcDoc.FirstSection.Body.AppendParagraph("Source document text. ");

                                                                         Document dstDoc = new Document();
                                                                         dstDoc.FirstSection.Body.AppendParagraph("Destination document text. ");

                                                                         // Append the source document to the destination document while preserving its formatting,
                                                                         // then save the source document to the local file system.
                                                                         dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
                                                                         dstDoc.Save(ArtifactsDir + "Document.AppendDocument.docx");

Shows how to append all the documents in a folder to the end of a template document.

Document dstDoc = new Document();

                                                                                               DocumentBuilder builder = new DocumentBuilder(dstDoc);
                                                                                               builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
                                                                                               builder.Writeln("Template Document");
                                                                                               builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;
                                                                                               builder.Writeln("Some content here");
                                                                                               // Append all unencrypted documents with the .doc extension
                                                                                               // from our local file system directory to the base document.
                                                                                               List<string> docFiles = Directory.GetFiles(MyDir, "*.doc").Where(item => item.EndsWith(".doc")).ToList();
                                                                                               foreach (string fileName in docFiles)
                                                                                               {
                                                                                                   FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);
                                                                                                   if (info.IsEncrypted)
                                                                                                       continue;

                                                                                                   Document srcDoc = new Document(fileName);
                                                                                                   dstDoc.AppendDocument(srcDoc, ImportFormatMode.UseDestinationStyles);
                                                                                               }

                                                                                               dstDoc.Save(ArtifactsDir + "Document.AppendAllDocumentsInFolder.doc");

AppendDocument(Document, ImportFormatMode, ImportFormatOptions)

Appends the specified document to the end of this document.

public void AppendDocument(Document srcDoc, ImportFormatMode importFormatMode, ImportFormatOptions importFormatOptions)

Parameters

srcDoc Document

The document to append.

importFormatMode ImportFormatMode

Specifies how to merge style formatting that clashes.

importFormatOptions ImportFormatOptions

Allows to specify options that affect formatting of a result document.

Examples

Shows how to manage list style clashes while appending a clone of a document to itself.

Document srcDoc = new Document(MyDir + "List item.docx");
                                                                                                  Document dstDoc = new Document(MyDir + "List item.docx");

                                                                                                  // If there is a clash of list styles, apply the list format of the source document.
                                                                                                  // Set the "KeepSourceNumbering" property to "false" to not import any list numbers into the destination document.
                                                                                                  // Set the "KeepSourceNumbering" property to "true" import all clashing
                                                                                                  // list style numbering with the same appearance that it had in the source document.
                                                                                                  DocumentBuilder builder = new DocumentBuilder(dstDoc);
                                                                                                  builder.MoveToDocumentEnd();
                                                                                                  builder.InsertBreak(BreakType.SectionBreakNewPage);

                                                                                                  ImportFormatOptions options = new ImportFormatOptions();
                                                                                                  options.KeepSourceNumbering = keepSourceNumbering;
                                                                                                  builder.InsertDocument(srcDoc, ImportFormatMode.KeepSourceFormatting, options);

                                                                                                  dstDoc.UpdateListLabels();

Shows how to manage list style clashes while inserting a document.

Document dstDoc = new Document();
                                                                             DocumentBuilder builder = new DocumentBuilder(dstDoc);
                                                                             builder.InsertBreak(BreakType.ParagraphBreak);

                                                                             dstDoc.Lists.Add(ListTemplate.NumberDefault);
                                                                             Aspose.Words.Lists.List docList = dstDoc.Lists[0];

                                                                             builder.ListFormat.List = docList;

                                                                             for (int i = 1; i <= 15; i++)
                                                                                 builder.Write($"List Item {i}\n");

                                                                             Document attachDoc = (Document)dstDoc.Clone(true);

                                                                             // If there is a clash of list styles, apply the list format of the source document.
                                                                             // Set the "KeepSourceNumbering" property to "false" to not import any list numbers into the destination document.
                                                                             // Set the "KeepSourceNumbering" property to "true" import all clashing
                                                                             // list style numbering with the same appearance that it had in the source document.
                                                                             ImportFormatOptions importOptions = new ImportFormatOptions();
                                                                             importOptions.KeepSourceNumbering = keepSourceNumbering;

                                                                             builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                                             builder.InsertDocument(attachDoc, ImportFormatMode.KeepSourceFormatting, importOptions);

                                                                             dstDoc.Save(ArtifactsDir + "DocumentBuilder.InsertDocumentAndResolveStyles.docx");

Shows how to manage list style clashes while appending a document.

// Load a document with text in a custom style and clone it.
                                                                             Document srcDoc = new Document(MyDir + "Custom list numbering.docx");
                                                                             Document dstDoc = srcDoc.Clone();

                                                                             // We now have two documents, each with an identical style named "CustomStyle".
                                                                             // Change the text color for one of the styles to set it apart from the other.
                                                                             dstDoc.Styles["CustomStyle"].Font.Color = Color.DarkRed;

                                                                             // If there is a clash of list styles, apply the list format of the source document.
                                                                             // Set the "KeepSourceNumbering" property to "false" to not import any list numbers into the destination document.
                                                                             // Set the "KeepSourceNumbering" property to "true" import all clashing
                                                                             // list style numbering with the same appearance that it had in the source document.
                                                                             ImportFormatOptions options = new ImportFormatOptions();
                                                                             options.KeepSourceNumbering = keepSourceNumbering;

                                                                             // Joining two documents that have different styles that share the same name causes a style clash.
                                                                             // We can specify an import format mode while appending documents to resolve this clash.
                                                                             dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepDifferentStyles, options);
                                                                             dstDoc.UpdateListLabels();

                                                                             dstDoc.Save(ArtifactsDir + "DocumentBuilder.AppendDocumentAndResolveStyles.docx");

Cleanup()

Cleans unused styles and lists from the document.

public void Cleanup()

Examples

Shows how to remove unused custom styles from a document.

Document doc = new Document();

                                                                    doc.Styles.Add(StyleType.List, "MyListStyle1");
                                                                    doc.Styles.Add(StyleType.List, "MyListStyle2");
                                                                    doc.Styles.Add(StyleType.Character, "MyParagraphStyle1");
                                                                    doc.Styles.Add(StyleType.Character, "MyParagraphStyle2");

                                                                    // Combined with the built-in styles, the document now has eight styles.
                                                                    // A custom style counts as "used" while applied to some part of the document,
                                                                    // which means that the four styles we added are currently unused.
                                                                    Assert.That(doc.Styles.Count, Is.EqualTo(8));

                                                                    // Apply a custom character style, and then a custom list style. Doing so will mark the styles as "used".
                                                                    DocumentBuilder builder = new DocumentBuilder(doc);
                                                                    builder.Font.Style = doc.Styles["MyParagraphStyle1"];
                                                                    builder.Writeln("Hello world!");

                                                                    Aspose.Words.Lists.List docList = doc.Lists.Add(doc.Styles["MyListStyle1"]);
                                                                    builder.ListFormat.List = docList;
                                                                    builder.Writeln("Item 1");
                                                                    builder.Writeln("Item 2");

                                                                    doc.Cleanup();

                                                                    Assert.That(doc.Styles.Count, Is.EqualTo(6));

                                                                    // Removing every node that a custom style is applied to marks it as "unused" again.
                                                                    // Run the Cleanup method again to remove them.
                                                                    doc.FirstSection.Body.RemoveAllChildren();
                                                                    doc.Cleanup();

                                                                    Assert.That(doc.Styles.Count, Is.EqualTo(4));

Cleanup(CleanupOptions)

Cleans unused styles and lists from the document depending on given Aspose.Words.CleanupOptions.

public void Cleanup(CleanupOptions options)

Parameters

options CleanupOptions

Examples

Shows how to remove all unused custom styles from a document.

Document doc = new Document();

                                                                        doc.Styles.Add(StyleType.List, "MyListStyle1");
                                                                        doc.Styles.Add(StyleType.List, "MyListStyle2");
                                                                        doc.Styles.Add(StyleType.Character, "MyParagraphStyle1");
                                                                        doc.Styles.Add(StyleType.Character, "MyParagraphStyle2");

                                                                        // Combined with the built-in styles, the document now has eight styles.
                                                                        // A custom style is marked as "used" while there is any text within the document
                                                                        // formatted in that style. This means that the 4 styles we added are currently unused.
                                                                        Assert.That(doc.Styles.Count, Is.EqualTo(8));

                                                                        // Apply a custom character style, and then a custom list style. Doing so will mark them as "used".
                                                                        DocumentBuilder builder = new DocumentBuilder(doc);
                                                                        builder.Font.Style = doc.Styles["MyParagraphStyle1"];
                                                                        builder.Writeln("Hello world!");

                                                                        Aspose.Words.Lists.List docList = doc.Lists.Add(doc.Styles["MyListStyle1"]);
                                                                        builder.ListFormat.List = docList;
                                                                        builder.Writeln("Item 1");
                                                                        builder.Writeln("Item 2");

                                                                        // Now, there is one unused character style and one unused list style.
                                                                        // The Cleanup() method, when configured with a CleanupOptions object, can target unused styles and remove them.
                                                                        CleanupOptions cleanupOptions = new CleanupOptions
                                                                        {
                                                                            UnusedLists = true, UnusedStyles = true, UnusedBuiltinStyles = true
                                                                        };

                                                                        doc.Cleanup(cleanupOptions);

                                                                        Assert.That(doc.Styles.Count, Is.EqualTo(4));

                                                                        // Removing every node that a custom style is applied to marks it as "unused" again. 
                                                                        // Rerun the Cleanup method to remove them.
                                                                        doc.FirstSection.Body.RemoveAllChildren();
                                                                        doc.Cleanup(cleanupOptions);

                                                                        Assert.That(doc.Styles.Count, Is.EqualTo(2));

Clone()

Performs a deep copy of the Aspose.Words.Document.

public Document Clone()

Returns

Document

The cloned document.

Examples

Shows how to deep clone a document.

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

                                              builder.Write("Hello world!");

                                              // Cloning will produce a new document with the same contents as the original,
                                              // but with a unique copy of each of the original document's nodes.
                                              Document clone = doc.Clone();

                                              Assert.That(clone.FirstSection.Body.FirstParagraph.Runs[0].Text, Is.EqualTo(doc.FirstSection.Body.FirstParagraph.Runs[0].GetText()));
                                              Assert.That(clone.FirstSection.Body.FirstParagraph.Runs[0].GetHashCode(), Is.Not.EqualTo(doc.FirstSection.Body.FirstParagraph.Runs[0].GetHashCode()));

Compare(Document, string, DateTime)

Compares this document with another document producing changes as number of edit and format revisions Aspose.Words.Revision.

public void Compare(Document document, string author, DateTime dateTime)

Parameters

document Document

Document to compare.

author string

Initials of the author to use for revisions.

dateTime DateTime

The date and time to use for revisions.

Examples

Shows how to compare documents.

Document docOriginal = new Document();
                                          DocumentBuilder builder = new DocumentBuilder(docOriginal);
                                          builder.Writeln("This is the original document.");

                                          Document docEdited = new Document();
                                          builder = new DocumentBuilder(docEdited);
                                          builder.Writeln("This is the edited document.");

                                          // Comparing documents with revisions will throw an exception.
                                          if (docOriginal.Revisions.Count == 0 && docEdited.Revisions.Count == 0)
                                              docOriginal.Compare(docEdited, "authorName", DateTime.Now);

                                          // After the comparison, the original document will gain a new revision
                                          // for every element that is different in the edited document.
                                          foreach (Revision r in docOriginal.Revisions)
                                          {
                                              Console.WriteLine($"Revision type: {r.RevisionType}, on a node of type \"{r.ParentNode.NodeType}\"");
                                              Console.WriteLine($"\tChanged text: \"{r.ParentNode.GetText()}\"");
                                          }

                                          // Accepting these revisions will transform the original document into the edited document.
                                          docOriginal.Revisions.AcceptAll();

                                          Assert.That(docEdited.GetText(), Is.EqualTo(docOriginal.GetText()));

Remarks

note

Documents must not have revisions before comparison.

Compare(Document, string, DateTime, CompareOptions)

Compares this document with another document producing changes as a number of edit and format revisions Aspose.Words.Revision. Allows to specify comparison options using Aspose.Words.Comparing.CompareOptions.

public void Compare(Document document, string author, DateTime dateTime, CompareOptions options)

Parameters

document Document

author string

dateTime DateTime

options CompareOptions

Examples

Shows how to filter specific types of document elements when making a comparison.

// Create the original document and populate it with various kinds of elements.
                                                                                            Document docOriginal = new Document();
                                                                                            DocumentBuilder builder = new DocumentBuilder(docOriginal);

                                                                                            // Paragraph text referenced with an endnote:
                                                                                            builder.Writeln("Hello world! This is the first paragraph.");
                                                                                            builder.InsertFootnote(FootnoteType.Endnote, "Original endnote text.");

                                                                                            // Table:
                                                                                            builder.StartTable();
                                                                                            builder.InsertCell();
                                                                                            builder.Write("Original cell 1 text");
                                                                                            builder.InsertCell();
                                                                                            builder.Write("Original cell 2 text");
                                                                                            builder.EndTable();

                                                                                            // Textbox:
                                                                                            Shape textBox = builder.InsertShape(ShapeType.TextBox, 150, 20);
                                                                                            builder.MoveTo(textBox.FirstParagraph);
                                                                                            builder.Write("Original textbox contents");

                                                                                            // DATE field:
                                                                                            builder.MoveTo(docOriginal.FirstSection.Body.AppendParagraph(""));
                                                                                            builder.InsertField(" DATE ");

                                                                                            // Comment:
                                                                                            Comment newComment = new Comment(docOriginal, "John Doe", "J.D.", DateTime.Now);
                                                                                            newComment.SetText("Original comment.");
                                                                                            builder.CurrentParagraph.AppendChild(newComment);

                                                                                            // Header:
                                                                                            builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
                                                                                            builder.Writeln("Original header contents.");

                                                                                            // Create a clone of our document and perform a quick edit on each of the cloned document's elements.
                                                                                            Document docEdited = (Document)docOriginal.Clone(true);
                                                                                            Paragraph firstParagraph = docEdited.FirstSection.Body.FirstParagraph;

                                                                                            firstParagraph.Runs[0].Text = "hello world! this is the first paragraph, after editing.";
                                                                                            firstParagraph.ParagraphFormat.Style = docEdited.Styles[StyleIdentifier.Heading1];
                                                                                            ((Footnote)docEdited.GetChild(NodeType.Footnote, 0, true)).FirstParagraph.Runs[1].Text = "Edited endnote text.";
                                                                                            ((Table)docEdited.GetChild(NodeType.Table, 0, true)).FirstRow.Cells[1].FirstParagraph.Runs[0].Text = "Edited Cell 2 contents";
                                                                                            ((Shape)docEdited.GetChild(NodeType.Shape, 0, true)).FirstParagraph.Runs[0].Text = "Edited textbox contents";
                                                                                            ((FieldDate)docEdited.Range.Fields[0]).UseLunarCalendar = true;
                                                                                            ((Comment)docEdited.GetChild(NodeType.Comment, 0, true)).FirstParagraph.Runs[0].Text = "Edited comment.";
                                                                                            docEdited.FirstSection.HeadersFooters[HeaderFooterType.HeaderPrimary].FirstParagraph.Runs[0].Text =
                                                                                                "Edited header contents.";

                                                                                            // Comparing documents creates a revision for every edit in the edited document.
                                                                                            // A CompareOptions object has a series of flags that can suppress revisions
                                                                                            // on each respective type of element, effectively ignoring their change.
                                                                                            CompareOptions compareOptions = new CompareOptions
                                                                                            {
                                                                                                CompareMoves = false,
                                                                                                IgnoreFormatting = false,
                                                                                                IgnoreCaseChanges = false,
                                                                                                IgnoreComments = false,
                                                                                                IgnoreTables = false,
                                                                                                IgnoreFields = false,
                                                                                                IgnoreFootnotes = false,
                                                                                                IgnoreTextboxes = false,
                                                                                                IgnoreHeadersAndFooters = false,
                                                                                                Target = ComparisonTargetType.New
                                                                                            };

                                                                                            docOriginal.Compare(docEdited, "John Doe", DateTime.Now, compareOptions);
                                                                                            docOriginal.Save(ArtifactsDir + "Revision.CompareOptions.docx");

CopyStylesFromTemplate(string)

Copies styles from the specified template to a document.

public void CopyStylesFromTemplate(string template)

Parameters

template string

Examples

Shows how to copy styles from one document to another.

// Create a document, and then add styles that we will copy to another document.
                                                                 Document template = new Document();

                                                                 Style style = template.Styles.Add(StyleType.Paragraph, "TemplateStyle1");
                                                                 style.Font.Name = "Times New Roman";
                                                                 style.Font.Color = Color.Navy;

                                                                 style = template.Styles.Add(StyleType.Paragraph, "TemplateStyle2");
                                                                 style.Font.Name = "Arial";
                                                                 style.Font.Color = Color.DeepSkyBlue;

                                                                 style = template.Styles.Add(StyleType.Paragraph, "TemplateStyle3");
                                                                 style.Font.Name = "Courier New";
                                                                 style.Font.Color = Color.RoyalBlue;

                                                                 Assert.That(template.Styles.Count, Is.EqualTo(7));

                                                                 // Create a document which we will copy the styles to.
                                                                 Document target = new Document();

                                                                 // Create a style with the same name as a style from the template document and add it to the target document.
                                                                 style = target.Styles.Add(StyleType.Paragraph, "TemplateStyle3");
                                                                 style.Font.Name = "Calibri";
                                                                 style.Font.Color = Color.Orange;

                                                                 Assert.That(target.Styles.Count, Is.EqualTo(5));

                                                                 // There are two ways of calling the method to copy all the styles from one document to another.
                                                                 // 1 -  Passing the template document object:
                                                                 target.CopyStylesFromTemplate(template);

                                                                 // Copying styles adds all styles from the template document to the target
                                                                 // and overwrites existing styles with the same name.
                                                                 Assert.That(target.Styles.Count, Is.EqualTo(7));

                                                                 Assert.That(target.Styles["TemplateStyle3"].Font.Name, Is.EqualTo("Courier New"));
                                                                 Assert.That(target.Styles["TemplateStyle3"].Font.Color.ToArgb(), Is.EqualTo(Color.RoyalBlue.ToArgb()));

                                                                 // 2 -  Passing the local system filename of a template document:
                                                                 target.CopyStylesFromTemplate(MyDir + "Rendering.docx");

                                                                 Assert.That(target.Styles.Count, Is.EqualTo(21));

Remarks

When styles are copied from a template to a document, like-named styles in the document are redefined to match the style descriptions in the template. Unique styles from the template are copied to the document. Unique styles in the document remain intact.

CopyStylesFromTemplate(Document)

Copies styles from the specified template to a document.

public void CopyStylesFromTemplate(Document template)

Parameters

template Document

Examples

Shows how to copies styles from the template to a document via Document.

Document template = new Document(MyDir + "Rendering.docx");
                                                                                   Document target = new Document(MyDir + "Document.docx");

                                                                                   target.CopyStylesFromTemplate(template);

Shows how to copy styles from one document to another.

// Create a document, and then add styles that we will copy to another document.
                                                                 Document template = new Document();

                                                                 Style style = template.Styles.Add(StyleType.Paragraph, "TemplateStyle1");
                                                                 style.Font.Name = "Times New Roman";
                                                                 style.Font.Color = Color.Navy;

                                                                 style = template.Styles.Add(StyleType.Paragraph, "TemplateStyle2");
                                                                 style.Font.Name = "Arial";
                                                                 style.Font.Color = Color.DeepSkyBlue;

                                                                 style = template.Styles.Add(StyleType.Paragraph, "TemplateStyle3");
                                                                 style.Font.Name = "Courier New";
                                                                 style.Font.Color = Color.RoyalBlue;

                                                                 Assert.That(template.Styles.Count, Is.EqualTo(7));

                                                                 // Create a document which we will copy the styles to.
                                                                 Document target = new Document();

                                                                 // Create a style with the same name as a style from the template document and add it to the target document.
                                                                 style = target.Styles.Add(StyleType.Paragraph, "TemplateStyle3");
                                                                 style.Font.Name = "Calibri";
                                                                 style.Font.Color = Color.Orange;

                                                                 Assert.That(target.Styles.Count, Is.EqualTo(5));

                                                                 // There are two ways of calling the method to copy all the styles from one document to another.
                                                                 // 1 -  Passing the template document object:
                                                                 target.CopyStylesFromTemplate(template);

                                                                 // Copying styles adds all styles from the template document to the target
                                                                 // and overwrites existing styles with the same name.
                                                                 Assert.That(target.Styles.Count, Is.EqualTo(7));

                                                                 Assert.That(target.Styles["TemplateStyle3"].Font.Name, Is.EqualTo("Courier New"));
                                                                 Assert.That(target.Styles["TemplateStyle3"].Font.Color.ToArgb(), Is.EqualTo(Color.RoyalBlue.ToArgb()));

                                                                 // 2 -  Passing the local system filename of a template document:
                                                                 target.CopyStylesFromTemplate(MyDir + "Rendering.docx");

                                                                 Assert.That(target.Styles.Count, Is.EqualTo(21));

Remarks

When styles are copied from a template to a document, like-named styles in the document are redefined to match the style descriptions in the template. Unique styles from the template are copied to the document. Unique styles in the document remain intact.

EnsureMinimum()

If the document contains no sections, creates one section with one paragraph.

public void EnsureMinimum()

Examples

Shows how to ensure that a document contains the minimal set of nodes required for editing its contents.

// A newly created document contains one child Section, which includes one child Body and one child Paragraph.
                                                                                                                   // We can edit the document body's contents by adding nodes such as Runs or inline Shapes to that paragraph.
                                                                                                                   Document doc = new Document();
                                                                                                                   NodeCollection nodes = doc.GetChildNodes(NodeType.Any, true);

                                                                                                                   Assert.That(nodes[0].NodeType, Is.EqualTo(NodeType.Section));
                                                                                                                   Assert.That(nodes[0].ParentNode, Is.EqualTo(doc));

                                                                                                                   Assert.That(nodes[1].NodeType, Is.EqualTo(NodeType.Body));
                                                                                                                   Assert.That(nodes[1].ParentNode, Is.EqualTo(nodes[0]));

                                                                                                                   Assert.That(nodes[2].NodeType, Is.EqualTo(NodeType.Paragraph));
                                                                                                                   Assert.That(nodes[2].ParentNode, Is.EqualTo(nodes[1]));

                                                                                                                   // This is the minimal set of nodes that we need to be able to edit the document.
                                                                                                                   // We will no longer be able to edit the document if we remove any of them.
                                                                                                                   doc.RemoveAllChildren();

                                                                                                                   Assert.That(doc.GetChildNodes(NodeType.Any, true).Count, Is.EqualTo(0));

                                                                                                                   // Call this method to make sure that the document has at least those three nodes so we can edit it again.
                                                                                                                   doc.EnsureMinimum();

                                                                                                                   Assert.That(nodes[0].NodeType, Is.EqualTo(NodeType.Section));
                                                                                                                   Assert.That(nodes[1].NodeType, Is.EqualTo(NodeType.Body));
                                                                                                                   Assert.That(nodes[2].NodeType, Is.EqualTo(NodeType.Paragraph));

                                                                                                                   ((Paragraph)nodes[2]).Runs.Add(new Run(doc, "Hello world!"));

ExpandTableStylesToDirectFormatting()

Converts formatting specified in table styles into direct formatting on tables in the document.

public void ExpandTableStylesToDirectFormatting()

Examples

Shows how to apply the properties of a table’s style directly to the table’s elements.

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

                                                                                                 Table table = builder.StartTable();
                                                                                                 builder.InsertCell();
                                                                                                 builder.Write("Hello world!");
                                                                                                 builder.EndTable();

                                                                                                 TableStyle tableStyle = (TableStyle)doc.Styles.Add(StyleType.Table, "MyTableStyle1");
                                                                                                 tableStyle.RowStripe = 3;
                                                                                                 tableStyle.CellSpacing = 5;
                                                                                                 tableStyle.Shading.BackgroundPatternColor = Color.AntiqueWhite;
                                                                                                 tableStyle.Borders.Color = Color.Blue;
                                                                                                 tableStyle.Borders.LineStyle = LineStyle.DotDash;

                                                                                                 table.Style = tableStyle;

                                                                                                 // This method concerns table style properties such as the ones we set above.
                                                                                                 doc.ExpandTableStylesToDirectFormatting();

                                                                                                 doc.Save(ArtifactsDir + "Document.TableStyleToDirectFormatting.docx");

Remarks

This method exists because this version of Aspose.Words provides only limited support for table styles (see below). This method might be useful when you load a DOCX or WordprocessingML document that contains tables formatted with table styles and you need to query formatting of tables, cells, paragraphs or text.

This version of Aspose.Words provides limited support for table styles as follows:

  • Table styles defined in DOCX or WordprocessingML documents are preserved as table styles when saving the document as DOCX or WordprocessingML.
  • Table styles defined in DOCX or WordprocessingML documents are automatically converted to direct formatting on tables when saving the document into any other format, rendering or printing.
  • Table styles defined in DOC documents are preserved as table styles when saving the document as DOC only.

ExtractPages(int, int, PageExtractOptions)

Returns the Aspose.Words.Document object representing the specified range of pages and the given page extract options.

public Document ExtractPages(int index, int count, PageExtractOptions options)

Parameters

index int

The zero-based index of the first page to extract.

count int

Number of pages to be extracted.

options PageExtractOptions

Provides options for managing the page extracting process.

Returns

Document

Remarks

The resulting document should look like the one in MS Word, as if we had performed ‘Print specific pages’ – the numbering, headers/footers and cross tables layout will be preserved. But due to a large number of nuances, appearing while reducing the number of pages, full match of the layout is a quiet complicated task requiring a lot of effort. Depending on the document complexity there might be slight differences in the resulting document contents layout comparing to the source document. Any feedback would be greatly appreciated.

ExtractPages(int, int)

Returns the Aspose.Words.Document object representing specified range of pages.

public Document ExtractPages(int index, int count)

Parameters

index int

The zero-based index of the first page to extract.

count int

Number of pages to be extracted.

Returns

Document

Examples

Shows how to get specified range of pages from the document.

Document doc = new Document(MyDir + "Layout entities.docx");

                                                                       doc = doc.ExtractPages(0, 2);

                                                                       doc.Save(ArtifactsDir + "Document.ExtractPages.docx");

Show how to reset the initial page numbering and save the NUMPAGE field.

Document doc = new Document(MyDir + "Page fields.docx");

                                                                                   // Default behavior:
                                                                                   // The extracted page numbering is the same as in the original document, as if we had selected "Print 2 pages" in MS Word.
                                                                                   // The start page will be set to 2 and the field indicating the number of pages will be removed
                                                                                   // and replaced with a constant value equal to the number of pages.
                                                                                   Document extractedDoc1 = doc.ExtractPages(1, 1);
                                                                                   extractedDoc1.Save(ArtifactsDir + "Document.ExtractPagesWithOptions.Default.docx");

                                                                                   // Altered behavior:
                                                                                   // The extracted page numbering is reset and a new one begins,
                                                                                   // as if we had copied the contents of the second page and pasted it into a new document.
                                                                                   // The start page will be set to 1 and the field indicating the number of pages will be left unchanged
                                                                                   // and will show the current number of pages.
                                                                                   PageExtractOptions extractOptions = new PageExtractOptions();
                                                                                   extractOptions.UpdatePageStartingNumber = false;
                                                                                   extractOptions.UnlinkPagesNumberFields = false;
                                                                                   Document extractedDoc2 = doc.ExtractPages(1, 1, extractOptions);
                                                                                   extractedDoc2.Save(ArtifactsDir + "Document.ExtractPagesWithOptions.Options.docx");

Remarks

The resulting document should look like the one in MS Word, as if we had performed ‘Print specific pages’ – the numbering, headers/footers and cross tables layout will be preserved. But due to a large number of nuances, appearing while reducing the number of pages, full match of the layout is a quiet complicated task requiring a lot of effort. Depending on the document complexity there might be slight differences in the resulting document contents layout comparing to the source document. Any feedback would be greatly appreciated.

GetPageInfo(int)

Gets the page size, orientation and other information about a page that might be useful for printing or rendering.

public PageInfo GetPageInfo(int pageIndex)

Parameters

pageIndex int

The 0-based page index.

Returns

PageInfo

Examples

Shows how to check whether the page is in color or not.

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

                                                                  // Check that the first page of the document is not colored.
                                                                  Assert.That(doc.GetPageInfo(0).Colored, Is.False);

JoinRunsWithSameFormatting()

Joins runs with same formatting in all paragraphs of the document.

public int JoinRunsWithSameFormatting()

Returns

int

Number of joins performed. When N adjacent runs are being joined they count as N - 1 joins.

Examples

Shows how to join runs in a document to reduce unneeded runs.

// Open a document that contains adjacent runs of text with identical formatting,
                                                                        // which commonly occurs if we edit the same paragraph multiple times in Microsoft Word.
                                                                        Document doc = new Document(MyDir + "Rendering.docx");

                                                                        // If any number of these runs are adjacent with identical formatting,
                                                                        // then the document may be simplified.
                                                                        Assert.That(doc.GetChildNodes(NodeType.Run, true).Count, Is.EqualTo(317));

                                                                        // Combine such runs with this method and verify the number of run joins that will take place.
                                                                        Assert.That(doc.JoinRunsWithSameFormatting(), Is.EqualTo(121));

                                                                        // The number of joins and the number of runs we have after the join
                                                                        // should add up the number of runs we had initially.
                                                                        Assert.That(doc.GetChildNodes(NodeType.Run, true).Count, Is.EqualTo(196));

Remarks

This is an optimization method. Some documents contain adjacent runs with same formatting. Usually this occurs if a document was intensively edited manually. You can reduce the document size and speed up further processing by joining these runs.

The operation checks every Aspose.Words.Paragraph node in the document for adjacent Aspose.Words.Run nodes having identical properties. It ignores unique identifiers used to track editing sessions of run creation and modification. First run in every joining sequence accumulates all text. Remaining runs are deleted from the document.

NormalizeFieldTypes()

Changes field type values Aspose.Words.Fields.FieldChar.FieldType of Aspose.Words.Fields.FieldStart, Aspose.Words.Fields.FieldSeparator, Aspose.Words.Fields.FieldEnd in the whole document so that they correspond to the field types contained in the field codes.

public void NormalizeFieldTypes()

Examples

Shows how to get the keep a field’s type up to date with its field code.

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

                                                                                   Field field = builder.InsertField("DATE", null);

                                                                                   // Aspose.Words automatically detects field types based on field codes.
                                                                                   Assert.That(field.Type, Is.EqualTo(FieldType.FieldDate));

                                                                                   // Manually change the raw text of the field, which determines the field code.
                                                                                   Run fieldText = (Run)doc.FirstSection.Body.FirstParagraph.GetChildNodes(NodeType.Run, true)[0];
                                                                                   fieldText.Text = "PAGE";

                                                                                   // Changing the field code has changed this field to one of a different type,
                                                                                   // but the field's type properties still display the old type.
                                                                                   Assert.That(field.GetFieldCode(), Is.EqualTo("PAGE"));
                                                                                   Assert.That(field.Type, Is.EqualTo(FieldType.FieldDate));
                                                                                   Assert.That(field.Start.FieldType, Is.EqualTo(FieldType.FieldDate));
                                                                                   Assert.That(field.Separator.FieldType, Is.EqualTo(FieldType.FieldDate));
                                                                                   Assert.That(field.End.FieldType, Is.EqualTo(FieldType.FieldDate));

                                                                                   // Update those properties with this method to display current value.
                                                                                   doc.NormalizeFieldTypes();

                                                                                   Assert.That(field.Type, Is.EqualTo(FieldType.FieldPage));
                                                                                   Assert.That(field.Start.FieldType, Is.EqualTo(FieldType.FieldPage));
                                                                                   Assert.That(field.Separator.FieldType, Is.EqualTo(FieldType.FieldPage));
                                                                                   Assert.That(field.End.FieldType, Is.EqualTo(FieldType.FieldPage));

Remarks

Use this method after document changes that affect field types.

To change field type values in a specific part of the document use Aspose.Words.Range.NormalizeFieldTypes.

Protect(ProtectionType)

Protects the document from changes without changing the existing password or assigns a random password.

public void Protect(ProtectionType type)

Parameters

type ProtectionType

Specifies the protection type for the document.

Examples

Shows how to turn off protection for a section.

Document doc = new Document();

                                                          DocumentBuilder builder = new DocumentBuilder(doc);
                                                          builder.Writeln("Section 1. Hello world!");
                                                          builder.InsertBreak(BreakType.SectionBreakNewPage);

                                                          builder.Writeln("Section 2. Hello again!");
                                                          builder.Write("Please enter text here: ");
                                                          builder.InsertTextInput("TextInput1", TextFormFieldType.Regular, "", "Placeholder text", 0);

                                                          // Apply write protection to every section in the document.
                                                          doc.Protect(ProtectionType.AllowOnlyFormFields);

                                                          // Turn off write protection for the first section.
                                                          doc.Sections[0].ProtectedForForms = false;

                                                          // In this output document, we will be able to edit the first section freely,
                                                          // and we will only be able to edit the contents of the form field in the second section.
                                                          doc.Save(ArtifactsDir + "Section.Protect.docx");

Remarks

When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

When you protect a document, and the document already has a protection password, the existing protection password is not changed.

When you protect a document, and the document does not have a protection password, this method assigns a random password that makes it impossible to unprotect the document in Microsoft Word, but you still can unprotect the document in Aspose.Words as it does not require a password when unprotecting.

Protect(ProtectionType, string)

Protects the document from changes and optionally sets a protection password.

public void Protect(ProtectionType type, string password)

Parameters

type ProtectionType

Specifies the protection type for the document.

password string

The password to protect the document with. Specify null or empty string if you want to protect the document without a password.

Examples

Shows how to protect and unprotect a document.

Document doc = new Document();
                                                         doc.Protect(ProtectionType.ReadOnly, "password");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         // If we open this document with Microsoft Word intending to edit it,
                                                         // we will need to apply the password to get through the protection.
                                                         doc.Save(ArtifactsDir + "Document.Protect.docx");

                                                         // Note that the protection only applies to Microsoft Word users opening our document.
                                                         // We have not encrypted the document in any way, and we do not need the password to open and edit it programmatically.
                                                         Document protectedDoc = new Document(ArtifactsDir + "Document.Protect.docx");

                                                         Assert.That(protectedDoc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         DocumentBuilder builder = new DocumentBuilder(protectedDoc);
                                                         builder.Writeln("Text added to a protected document.");
                                                         // There are two ways of removing protection from a document.
                                                         // 1 - With no password:
                                                         doc.Unprotect();

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.NoProtection));

                                                         doc.Protect(ProtectionType.ReadOnly, "NewPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         doc.Unprotect("WrongPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         // 2 - With the correct password:
                                                         doc.Unprotect("NewPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.NoProtection));

Remarks

When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

Note that document protection is different from write protection. Write protection is specified using the Aspose.Words.Document.WriteProtection.

RemoveBlankPages()

Removes blank pages from the document.

public List<int> RemoveBlankPages()

Returns

List < int >

List of page numbers has been considered as blank and removed.

Examples

Shows how to remove blank pages from the document.

Document doc = new Document(MyDir + "Blank pages.docx");
                                                             Assert.That(doc.PageCount, Is.EqualTo(2));
                                                             doc.RemoveBlankPages();
                                                             doc.UpdatePageLayout();
                                                             Assert.That(doc.PageCount, Is.EqualTo(1));

Remarks

The resulting document will not contain pages considered to be blank while other content, including numbering, headers/footers and overall layout should remain unchanged.

Page is considered to be blank when body of the page have no visible content, for example, empty table having no borders will be considered as invisible and therefore page will be detected as blank.

RemoveExternalSchemaReferences()

Removes external XML schema references from this document.

public void RemoveExternalSchemaReferences()

Examples

Shows how to remove all external XML schema references from a document.

Document doc = new Document(MyDir + "External XML schema.docx");

                                                                                  doc.RemoveExternalSchemaReferences();

RemoveMacros()

Removes all macros (the VBA project) as well as toolbars and command customizations from the document.

public void RemoveMacros()

Examples

Shows how to remove all macros from a document.

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

                                                          Assert.That(doc.HasMacros, Is.True);
                                                          Assert.That(doc.VbaProject.Name, Is.EqualTo("Project"));

                                                          // Remove the document's VBA project, along with all its macros.
                                                          doc.RemoveMacros();

                                                          Assert.That(doc.HasMacros, Is.False);
                                                          Assert.That(doc.VbaProject, Is.Null);

Remarks

By removing all macros from a document you can ensure the document contains no macro viruses.

RenderToScale(int, SKCanvas, float, float, float)

[CLSCompliant(false)]
public SizeF RenderToScale(int pageIndex, SKCanvas graphics, float x, float y, float scale)

Parameters

pageIndex int

graphics SKCanvas

x float

y float

scale float

Returns

SizeF

RenderToSize(int, SKCanvas, float, float, float, float)

[CLSCompliant(false)]
public float RenderToSize(int pageIndex, SKCanvas graphics, float x, float y, float width, float height)

Parameters

pageIndex int

graphics SKCanvas

x float

y float

width float

height float

Returns

float

Save(string)

Saves the document to a file. Automatically determines the save format from the extension.

public SaveOutputParameters Save(string fileName)

Parameters

fileName string

The name for the document. If a document with the specified file name already exists, the existing document is overwritten.

Returns

SaveOutputParameters

Additional information that you can optionally use.

Examples

Shows how to open a document and convert it to .PDF.

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

                                                               doc.Save(ArtifactsDir + "Document.ConvertToPdf.pdf");

Shows how to convert a PDF to a .docx.

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

                                                 builder.Write("Hello world!");

                                                 doc.Save(ArtifactsDir + "PDF2Word.ConvertPdfToDocx.pdf");

                                                 // Load the PDF document that we just saved, and convert it to .docx.
                                                 Document pdfDoc = new Document(ArtifactsDir + "PDF2Word.ConvertPdfToDocx.pdf");

                                                 pdfDoc.Save(ArtifactsDir + "PDF2Word.ConvertPdfToDocx.docx");

Save(string, SaveFormat)

Saves the document to a file in the specified format.

public SaveOutputParameters Save(string fileName, SaveFormat saveFormat)

Parameters

fileName string

The name for the document. If a document with the specified file name already exists, the existing document is overwritten.

saveFormat SaveFormat

The format in which to save the document.

Returns

SaveOutputParameters

Additional information that you can optionally use.

Examples

Shows how to convert from DOCX to HTML format.

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

                                                         doc.Save(ArtifactsDir + "Document.ConvertToHtml.html", SaveFormat.Html);

Save(string, SaveOptions)

Saves the document to a file using the specified save options.

public SaveOutputParameters Save(string fileName, SaveOptions saveOptions)

Parameters

fileName string

The name for the document. If a document with the specified file name already exists, the existing document is overwritten.

saveOptions SaveOptions

Specifies the options that control how the document is saved. Can be null.

Returns

SaveOutputParameters

Additional information that you can optionally use.

Examples

Shows how to improve the quality of a rendered document with SaveOptions.

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

                                                                                    builder.Font.Size = 60;
                                                                                    builder.Writeln("Some text.");

                                                                                    SaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg);
                                                                                    doc.Save(ArtifactsDir + "Document.ImageSaveOptions.Default.jpg", options);

                                                                                    options.UseAntiAliasing = true;
                                                                                    options.UseHighQualityRendering = true;

                                                                                    doc.Save(ArtifactsDir + "Document.ImageSaveOptions.HighQuality.jpg", options);

Shows how to convert a PDF to a .docx and customize the saving process with a SaveOptions object.

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

                                                                                                            builder.Writeln("Hello world!");

                                                                                                            doc.Save(ArtifactsDir + "PDF2Word.ConvertPdfToDocxCustom.pdf");

                                                                                                            // Load the PDF document that we just saved, and convert it to .docx.
                                                                                                            Document pdfDoc = new Document(ArtifactsDir + "PDF2Word.ConvertPdfToDocxCustom.pdf");

                                                                                                            OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(SaveFormat.Docx);

                                                                                                            // Set the "Password" property to encrypt the saved document with a password.
                                                                                                            saveOptions.Password = "MyPassword";

                                                                                                            pdfDoc.Save(ArtifactsDir + "PDF2Word.ConvertPdfToDocxCustom.docx", saveOptions);

Shows how to render every page of a document to a separate TIFF image.

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

                                                                                 builder.Writeln("Page 1.");
                                                                                 builder.InsertBreak(BreakType.PageBreak);
                                                                                 builder.Writeln("Page 2.");
                                                                                 builder.InsertImage(ImageDir + "Logo.jpg");
                                                                                 builder.InsertBreak(BreakType.PageBreak);
                                                                                 builder.Writeln("Page 3.");

                                                                                 // Create an "ImageSaveOptions" object which we can pass to the document's "Save" method
                                                                                 // to modify the way in which that method renders the document into an image.
                                                                                 ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff);

                                                                                 for (int i = 0; i < doc.PageCount; i++)
                                                                                 {
                                                                                     // Set the "PageSet" property to the number of the first page from
                                                                                     // which to start rendering the document from.
                                                                                     options.PageSet = new PageSet(i);
                                                                                     // Export page at 2325x5325 pixels and 600 dpi.
                                                                                     options.Resolution = 600;
                                                                                     options.ImageSize = new Size(2325, 5325);

                                                                                     doc.Save(ArtifactsDir + $"ImageSaveOptions.PageByPage.{i + 1}.tiff", options);
                                                                                 }

Shows how to render one page from a document to a JPEG image.

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

                                                                        builder.Writeln("Page 1.");
                                                                        builder.InsertBreak(BreakType.PageBreak);
                                                                        builder.Writeln("Page 2.");
                                                                        builder.InsertImage(ImageDir + "Logo.jpg");
                                                                        builder.InsertBreak(BreakType.PageBreak);
                                                                        builder.Writeln("Page 3.");

                                                                        // Create an "ImageSaveOptions" object which we can pass to the document's "Save" method
                                                                        // to modify the way in which that method renders the document into an image.
                                                                        ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg);
                                                                        // Set the "PageSet" to "1" to select the second page via
                                                                        // the zero-based index to start rendering the document from.
                                                                        options.PageSet = new PageSet(1);

                                                                        // When we save the document to the JPEG format, Aspose.Words only renders one page.
                                                                        // This image will contain one page starting from page two,
                                                                        // which will just be the second page of the original document.
                                                                        doc.Save(ArtifactsDir + "ImageSaveOptions.OnePage.jpg", options);

Shows how to configure compression while saving a document as a JPEG.

Document doc = new Document();
                                                                                DocumentBuilder builder = new DocumentBuilder(doc);
                                                                                builder.InsertImage(ImageDir + "Logo.jpg");

                                                                                // Create an "ImageSaveOptions" object which we can pass to the document's "Save" method
                                                                                // to modify the way in which that method renders the document into an image.
                                                                                ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg);
                                                                                // Set the "JpegQuality" property to "10" to use stronger compression when rendering the document.
                                                                                // This will reduce the file size of the document, but the image will display more prominent compression artifacts.
                                                                                imageOptions.JpegQuality = 10;
                                                                                doc.Save(ArtifactsDir + "ImageSaveOptions.JpegQuality.HighCompression.jpg", imageOptions);

                                                                                // Set the "JpegQuality" property to "100" to use weaker compression when rending the document.
                                                                                // This will improve the quality of the image at the cost of an increased file size.
                                                                                imageOptions.JpegQuality = 100;
                                                                                doc.Save(ArtifactsDir + "ImageSaveOptions.JpegQuality.HighQuality.jpg", imageOptions);

Shows how to convert a whole document to PDF with three levels in the document outline.

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

                                                                                                  // Insert headings of levels 1 to 5.
                                                                                                  builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

                                                                                                  Assert.That(builder.ParagraphFormat.IsHeading, Is.True);

                                                                                                  builder.Writeln("Heading 1");

                                                                                                  builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

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

                                                                                                  builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;

                                                                                                  builder.Writeln("Heading 1.2.1");
                                                                                                  builder.Writeln("Heading 1.2.2");

                                                                                                  builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading4;

                                                                                                  builder.Writeln("Heading 1.2.2.1");
                                                                                                  builder.Writeln("Heading 1.2.2.2");

                                                                                                  builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading5;

                                                                                                  builder.Writeln("Heading 1.2.2.2.1");
                                                                                                  builder.Writeln("Heading 1.2.2.2.2");

                                                                                                  // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method
                                                                                                  // to modify how that method converts the document to .PDF.
                                                                                                  PdfSaveOptions options = new PdfSaveOptions();

                                                                                                  // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body.
                                                                                                  // Clicking on an entry in this outline will take us to the location of its respective heading.
                                                                                                  // Set the "HeadingsOutlineLevels" property to "4" to exclude all headings whose levels are above 4 from the outline.
                                                                                                  options.OutlineOptions.HeadingsOutlineLevels = 4;

                                                                                                  // If an outline entry has subsequent entries of a higher level inbetween itself and the next entry of the same or lower level,
                                                                                                  // an arrow will appear to the left of the entry. This entry is the "owner" of several such "sub-entries".
                                                                                                  // In our document, the outline entries from the 5th heading level are sub-entries of the second 4th level outline entry,
                                                                                                  // the 4th and 5th heading level entries are sub-entries of the second 3rd level entry, and so on.
                                                                                                  // In the outline, we can click on the arrow of the "owner" entry to collapse/expand all its sub-entries.
                                                                                                  // Set the "ExpandedOutlineLevels" property to "2" to automatically expand all heading level 2 and lower outline entries
                                                                                                  // and collapse all level and 3 and higher entries when we open the document.
                                                                                                  options.OutlineOptions.ExpandedOutlineLevels = 2;

                                                                                                  doc.Save(ArtifactsDir + "PdfSaveOptions.ExpandedOutlineLevels.pdf", options);

Save(Stream, SaveFormat)

Saves the document to a stream using the specified format.

public SaveOutputParameters Save(Stream stream, SaveFormat saveFormat)

Parameters

stream Stream

Stream where to save the document.

saveFormat SaveFormat

The format in which to save the document.

Returns

SaveOutputParameters

Additional information that you can optionally use.

Examples

Shows how to save a document to a stream.

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

                                                    using (MemoryStream dstStream = new MemoryStream())
                                                    {
                                                        doc.Save(dstStream, SaveFormat.Docx);

                                                        // Verify that the stream contains the document.
                                                        Assert.That(new Document(dstStream).GetText().Trim(), Is.EqualTo("Hello World!\r\rHello Word!\r\r\rHello World!"));
                                                    }

Shows how to save a document to an image via stream, and then read the image from that stream.

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

                                                                                                                     builder.Font.Name = "Times New Roman";
                                                                                                                     builder.Font.Size = 24;
                                                                                                                     builder.Writeln("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");

                                                                                                                     builder.InsertImage(ImageDir + "Logo.jpg");

                                                                                                         #if NET461_OR_GREATER || JAVA
                                                                                                                     using (MemoryStream stream = new MemoryStream())
                                                                                                                     {
                                                                                                                         doc.Save(stream, SaveFormat.Bmp);

                                                                                                                         stream.Position = 0;

                                                                                                                         // Read the stream back into an image.
                                                                                                                         using (Image image = Image.FromStream(stream))
                                                                                                                         {
                                                                                                                             Assert.That(image.RawFormat, Is.EqualTo(ImageFormat.Bmp));
                                                                                                                             Assert.That(image.Width, Is.EqualTo(816));
                                                                                                                             Assert.That(image.Height, Is.EqualTo(1056));
                                                                                                                         }
                                                                                                                     }
                                                                                                         #elif NET5_0_OR_GREATER
                                                                                                                     using (MemoryStream stream = new MemoryStream())
                                                                                                                     {
                                                                                                                         doc.Save(stream, SaveFormat.Bmp);

                                                                                                                         stream.Position = 0;

                                                                                                                         SKCodec codec = SKCodec.Create(stream);
                                                                                                                         Assert.That(SKEncodedImageFormat.Bmp, Is.EqualTo(codec.EncodedFormat));

                                                                                                                         stream.Position = 0;

                                                                                                                         using (SKBitmap image = SKBitmap.Decode(stream))
                                                                                                                         {
                                                                                                                             Assert.That(816, Is.EqualTo(image.Width));
                                                                                                                             Assert.That(1056, Is.EqualTo(image.Height));
                                                                                                                         }
                                                                                                                     }
                                                                                                         #endif

Save(Stream, SaveOptions)

Saves the document to a stream using the specified save options.

public SaveOutputParameters Save(Stream stream, SaveOptions saveOptions)

Parameters

stream Stream

Stream where to save the document.

saveOptions SaveOptions

Specifies the options that control how the document is saved. Can be null. If this is null, the document will be saved in the binary DOC format.

Returns

SaveOutputParameters

Additional information that you can optionally use.

Examples

Shows how to convert only some of the pages in a document to PDF.

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

                                                                            builder.Writeln("Page 1.");
                                                                            builder.InsertBreak(BreakType.PageBreak);
                                                                            builder.Writeln("Page 2.");
                                                                            builder.InsertBreak(BreakType.PageBreak);
                                                                            builder.Writeln("Page 3.");

                                                                            using (Stream stream = File.Create(ArtifactsDir + "PdfSaveOptions.OnePage.pdf"))
                                                                            {
                                                                                // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method
                                                                                // to modify how that method converts the document to .PDF.
                                                                                PdfSaveOptions options = new PdfSaveOptions();

                                                                                // Set the "PageIndex" to "1" to render a portion of the document starting from the second page.
                                                                                options.PageSet = new PageSet(1);

                                                                                // This document will contain one page starting from page two, which will only contain the second page.
                                                                                doc.Save(stream, options);
                                                                            }

StartTrackRevisions(string, DateTime)

Starts automatically marking all further changes you make to the document programmatically as revision changes.

public void StartTrackRevisions(string author, DateTime dateTime)

Parameters

author string

Initials of the author to use for revisions.

dateTime DateTime

The date and time to use for revisions.

Examples

Shows how to track revisions while editing a document.

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

                                                                 // Editing a document usually does not count as a revision until we begin tracking them.
                                                                 builder.Write("Hello world! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(0));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[0].IsInsertRevision, Is.False);

                                                                 doc.StartTrackRevisions("John Doe");

                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[1].IsInsertRevision, Is.True);
                                                                 Assert.That(doc.Revisions[0].Author, Is.EqualTo("John Doe"));
                                                                 Assert.That((DateTime.Now - doc.Revisions[0].DateTime).Milliseconds <= 10, Is.True);

                                                                 // Stop tracking revisions to not count any future edits as revisions.
                                                                 doc.StopTrackRevisions();
                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[2].IsInsertRevision, Is.False);

                                                                 // Creating revisions gives them a date and time of the operation.
                                                                 // We can disable this by passing DateTime.MinValue when we start tracking revisions.
                                                                 doc.StartTrackRevisions("John Doe", DateTime.MinValue);
                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(2));
                                                                 Assert.That(doc.Revisions[1].Author, Is.EqualTo("John Doe"));
                                                                 Assert.That(doc.Revisions[1].DateTime, Is.EqualTo(DateTime.MinValue));

                                                                 // We can accept/reject these revisions programmatically
                                                                 // by calling methods such as Document.AcceptAllRevisions, or each revision's Accept method.
                                                                 // In Microsoft Word, we can process them manually via "Review" -> "Changes".
                                                                 doc.Save(ArtifactsDir + "Revision.StartTrackRevisions.docx");

Remarks

If you call this method and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.

Currently Aspose.Words supports tracking of node insertions and deletions only. Formatting changes are not recorded as revisions.

Automatic tracking of changes is supported both when modifying this document through node manipulations as well as when using Aspose.Words.DocumentBuilder

This method does not change the Aspose.Words.Document.TrackRevisions option and does not use its value for the purposes of revision tracking.

See Also

Document . StopTrackRevisions ()

StartTrackRevisions(string)

Starts automatically marking all further changes you make to the document programmatically as revision changes.

public void StartTrackRevisions(string author)

Parameters

author string

Initials of the author to use for revisions.

Examples

Shows how to track revisions while editing a document.

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

                                                                 // Editing a document usually does not count as a revision until we begin tracking them.
                                                                 builder.Write("Hello world! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(0));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[0].IsInsertRevision, Is.False);

                                                                 doc.StartTrackRevisions("John Doe");

                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[1].IsInsertRevision, Is.True);
                                                                 Assert.That(doc.Revisions[0].Author, Is.EqualTo("John Doe"));
                                                                 Assert.That((DateTime.Now - doc.Revisions[0].DateTime).Milliseconds <= 10, Is.True);

                                                                 // Stop tracking revisions to not count any future edits as revisions.
                                                                 doc.StopTrackRevisions();
                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[2].IsInsertRevision, Is.False);

                                                                 // Creating revisions gives them a date and time of the operation.
                                                                 // We can disable this by passing DateTime.MinValue when we start tracking revisions.
                                                                 doc.StartTrackRevisions("John Doe", DateTime.MinValue);
                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(2));
                                                                 Assert.That(doc.Revisions[1].Author, Is.EqualTo("John Doe"));
                                                                 Assert.That(doc.Revisions[1].DateTime, Is.EqualTo(DateTime.MinValue));

                                                                 // We can accept/reject these revisions programmatically
                                                                 // by calling methods such as Document.AcceptAllRevisions, or each revision's Accept method.
                                                                 // In Microsoft Word, we can process them manually via "Review" -> "Changes".
                                                                 doc.Save(ArtifactsDir + "Revision.StartTrackRevisions.docx");

Remarks

If you call this method and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.

Currently Aspose.Words supports tracking of node insertions and deletions only. Formatting changes are not recorded as revisions.

Automatic tracking of changes is supported both when modifying this document through node manipulations as well as when using Aspose.Words.DocumentBuilder

This method does not change the Aspose.Words.Document.TrackRevisions option and does not use its value for the purposes of revision tracking.

See Also

Document . StopTrackRevisions ()

StopTrackRevisions()

Stops automatic marking of document changes as revisions.

public void StopTrackRevisions()

Examples

Shows how to track revisions while editing a document.

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

                                                                 // Editing a document usually does not count as a revision until we begin tracking them.
                                                                 builder.Write("Hello world! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(0));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[0].IsInsertRevision, Is.False);

                                                                 doc.StartTrackRevisions("John Doe");

                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[1].IsInsertRevision, Is.True);
                                                                 Assert.That(doc.Revisions[0].Author, Is.EqualTo("John Doe"));
                                                                 Assert.That((DateTime.Now - doc.Revisions[0].DateTime).Milliseconds <= 10, Is.True);

                                                                 // Stop tracking revisions to not count any future edits as revisions.
                                                                 doc.StopTrackRevisions();
                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(1));
                                                                 Assert.That(doc.FirstSection.Body.Paragraphs[0].Runs[2].IsInsertRevision, Is.False);

                                                                 // Creating revisions gives them a date and time of the operation.
                                                                 // We can disable this by passing DateTime.MinValue when we start tracking revisions.
                                                                 doc.StartTrackRevisions("John Doe", DateTime.MinValue);
                                                                 builder.Write("Hello again! ");

                                                                 Assert.That(doc.Revisions.Count, Is.EqualTo(2));
                                                                 Assert.That(doc.Revisions[1].Author, Is.EqualTo("John Doe"));
                                                                 Assert.That(doc.Revisions[1].DateTime, Is.EqualTo(DateTime.MinValue));

                                                                 // We can accept/reject these revisions programmatically
                                                                 // by calling methods such as Document.AcceptAllRevisions, or each revision's Accept method.
                                                                 // In Microsoft Word, we can process them manually via "Review" -> "Changes".
                                                                 doc.Save(ArtifactsDir + "Revision.StartTrackRevisions.docx");

See Also

Document . StartTrackRevisions ( string , DateTime )

UnlinkFields()

Unlinks fields in the whole document.

public void UnlinkFields()

Examples

Shows how to unlink all fields in the document.

Document doc = new Document(MyDir + "Linked fields.docx");

                                                          doc.UnlinkFields();

Remarks

Replaces all the fields in the whole document with their most recent results.

To unlink fields in a specific part of the document use Aspose.Words.Range.UnlinkFields.

Unprotect()

Removes protection from the document regardless of the password.

public void Unprotect()

Examples

Shows how to protect and unprotect a document.

Document doc = new Document();
                                                         doc.Protect(ProtectionType.ReadOnly, "password");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         // If we open this document with Microsoft Word intending to edit it,
                                                         // we will need to apply the password to get through the protection.
                                                         doc.Save(ArtifactsDir + "Document.Protect.docx");

                                                         // Note that the protection only applies to Microsoft Word users opening our document.
                                                         // We have not encrypted the document in any way, and we do not need the password to open and edit it programmatically.
                                                         Document protectedDoc = new Document(ArtifactsDir + "Document.Protect.docx");

                                                         Assert.That(protectedDoc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         DocumentBuilder builder = new DocumentBuilder(protectedDoc);
                                                         builder.Writeln("Text added to a protected document.");
                                                         // There are two ways of removing protection from a document.
                                                         // 1 - With no password:
                                                         doc.Unprotect();

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.NoProtection));

                                                         doc.Protect(ProtectionType.ReadOnly, "NewPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         doc.Unprotect("WrongPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         // 2 - With the correct password:
                                                         doc.Unprotect("NewPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.NoProtection));

Remarks

This method unprotects the document even if it has a protection password.

Note that document protection is different from write protection. Write protection is specified using the Aspose.Words.Document.WriteProtection.

Unprotect(string)

Removes protection from the document if a correct password is specified.

public bool Unprotect(string password)

Parameters

password string

The password to unprotect the document with.

Returns

bool

true if a correct password was specified and the document was unprotected.

Examples

Shows how to protect and unprotect a document.

Document doc = new Document();
                                                         doc.Protect(ProtectionType.ReadOnly, "password");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         // If we open this document with Microsoft Word intending to edit it,
                                                         // we will need to apply the password to get through the protection.
                                                         doc.Save(ArtifactsDir + "Document.Protect.docx");

                                                         // Note that the protection only applies to Microsoft Word users opening our document.
                                                         // We have not encrypted the document in any way, and we do not need the password to open and edit it programmatically.
                                                         Document protectedDoc = new Document(ArtifactsDir + "Document.Protect.docx");

                                                         Assert.That(protectedDoc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         DocumentBuilder builder = new DocumentBuilder(protectedDoc);
                                                         builder.Writeln("Text added to a protected document.");
                                                         // There are two ways of removing protection from a document.
                                                         // 1 - With no password:
                                                         doc.Unprotect();

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.NoProtection));

                                                         doc.Protect(ProtectionType.ReadOnly, "NewPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         doc.Unprotect("WrongPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.ReadOnly));

                                                         // 2 - With the correct password:
                                                         doc.Unprotect("NewPassword");

                                                         Assert.That(doc.ProtectionType, Is.EqualTo(ProtectionType.NoProtection));

Remarks

This method unprotects the document only if a correct password is specified.

Note that document protection is different from write protection. Write protection is specified using the Aspose.Words.Document.WriteProtection.

UpdateActualReferenceMarks()

Updates the Aspose.Words.Notes.Footnote.ActualReferenceMark property of all footnotes and endnotes in the document.

public void UpdateActualReferenceMarks()

Examples

Shows how to get actual footnote reference mark.

Document doc = new Document(MyDir + "Footnotes and endnotes.docx");

                                                           Footnote footnote = (Footnote)doc.GetChild(NodeType.Footnote, 1, true);
                                                           doc.UpdateFields();
                                                           doc.UpdateActualReferenceMarks();

                                                           Assert.That(footnote.ActualReferenceMark, Is.EqualTo("1"));

Remarks

Updating fields (Aspose.Words.Document.UpdateFields) may be necessary to get the correct result.

UpdateFields()

Updates the values of fields in the whole document.

public void UpdateFields()

Examples

Shows to use the QUOTE field.

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

                                        // Insert a QUOTE field, which will display the value of its Text property.
                                        FieldQuote field = (FieldQuote)builder.InsertField(FieldType.FieldQuote, true);
                                        field.Text = "\"Quoted text\"";

                                        Assert.That(field.GetFieldCode(), Is.EqualTo(" QUOTE  \"\\\"Quoted text\\\"\""));

                                        // Insert a QUOTE field and nest a DATE field inside it.
                                        // DATE fields update their value to the current date every time we open the document using Microsoft Word.
                                        // Nesting the DATE field inside the QUOTE field like this will freeze its value
                                        // to the date when we created the document.
                                        builder.Write("\nDocument creation date: ");
                                        field = (FieldQuote)builder.InsertField(FieldType.FieldQuote, true);
                                        builder.MoveTo(field.Separator);
                                        builder.InsertField(FieldType.FieldDate, true);

                                        Assert.That(field.GetFieldCode(), Is.EqualTo(" QUOTE \u0013 DATE \u0014" + DateTime.Now.Date.ToShortDateString() + "\u0015"));

                                        // Update all the fields to display their correct results.
                                        doc.UpdateFields();

                                        Assert.That(doc.Range.Fields[0].Result, Is.EqualTo("\"Quoted text\""));

                                        doc.Save(ArtifactsDir + "Field.QUOTE.docx");

Shows how to set user details, and display them using fields.

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

                                                                        // Create a UserInformation object and set it as the data source for fields that display user information.
                                                                        UserInformation userInformation = new UserInformation
                                                                        {
                                                                            Name = "John Doe",
                                                                            Initials = "J. D.",
                                                                            Address = "123 Main Street"
                                                                        };
                                                                        doc.FieldOptions.CurrentUser = userInformation;

                                                                        // Insert USERNAME, USERINITIALS, and USERADDRESS fields, which display values of
                                                                        // the respective properties of the UserInformation object that we have created above. 
                                                                        Assert.That(builder.InsertField(" USERNAME ").Result, Is.EqualTo(userInformation.Name));
                                                                        Assert.That(builder.InsertField(" USERINITIALS ").Result, Is.EqualTo(userInformation.Initials));
                                                                        Assert.That(builder.InsertField(" USERADDRESS ").Result, Is.EqualTo(userInformation.Address));

                                                                        // The field options object also has a static default user that fields from all documents can refer to.
                                                                        UserInformation.DefaultUser.Name = "Default User";
                                                                        UserInformation.DefaultUser.Initials = "D. U.";
                                                                        UserInformation.DefaultUser.Address = "One Microsoft Way";
                                                                        doc.FieldOptions.CurrentUser = UserInformation.DefaultUser;

                                                                        Assert.That(builder.InsertField(" USERNAME ").Result, Is.EqualTo("Default User"));
                                                                        Assert.That(builder.InsertField(" USERINITIALS ").Result, Is.EqualTo("D. U."));
                                                                        Assert.That(builder.InsertField(" USERADDRESS ").Result, Is.EqualTo("One Microsoft Way"));

                                                                        doc.UpdateFields();
                                                                        doc.Save(ArtifactsDir + "FieldOptions.CurrentUser.docx");

Shows how to insert a Table of contents (TOC) into a document using heading styles as entries.

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

                                                                                                         // Insert a table of contents for the first page of the document.
                                                                                                         // Configure the table to pick up paragraphs with headings of levels 1 to 3.
                                                                                                         // Also, set its entries to be hyperlinks that will take us
                                                                                                         // to the location of the heading when left-clicked in Microsoft Word.
                                                                                                         builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
                                                                                                         builder.InsertBreak(BreakType.PageBreak);

                                                                                                         // Populate the table of contents by adding paragraphs with heading styles.
                                                                                                         // Each such heading with a level between 1 and 3 will create an entry in the table.
                                                                                                         builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
                                                                                                         builder.Writeln("Heading 1");

                                                                                                         builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
                                                                                                         builder.Writeln("Heading 1.1");
                                                                                                         builder.Writeln("Heading 1.2");

                                                                                                         builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
                                                                                                         builder.Writeln("Heading 2");
                                                                                                         builder.Writeln("Heading 3");

                                                                                                         builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
                                                                                                         builder.Writeln("Heading 3.1");

                                                                                                         builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;
                                                                                                         builder.Writeln("Heading 3.1.1");
                                                                                                         builder.Writeln("Heading 3.1.2");
                                                                                                         builder.Writeln("Heading 3.1.3");

                                                                                                         builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading4;
                                                                                                         builder.Writeln("Heading 3.1.3.1");
                                                                                                         builder.Writeln("Heading 3.1.3.2");

                                                                                                         builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
                                                                                                         builder.Writeln("Heading 3.2");
                                                                                                         builder.Writeln("Heading 3.3");

                                                                                                         // A table of contents is a field of a type that needs to be updated to show an up-to-date result.
                                                                                                         doc.UpdateFields();
                                                                                                         doc.Save(ArtifactsDir + "DocumentBuilder.InsertToc.docx");

Remarks

<p>When you open, modify and then save a document, Aspose.Words does not update fields automatically, it keeps them intact.

Therefore, you would usually want to call this method before saving if you have modified the document programmatically and want to make sure the proper (calculated) field values appear in the saved document.

There is no need to update fields after executing a mail merge because mail merge is a kind of field update and automatically updates all fields in the document.

This method does not update all field types. For the detailed list of supported field types, see the Programmers Guide.

This method does not update fields that are related to the page layout algorithms (e.g. PAGE, PAGES, PAGEREF). The page layout-related fields are updated when you render a document or call Aspose.Words.Document.UpdatePageLayout.

Use the Aspose.Words.Document.NormalizeFieldTypes method before fields updating if there were document changes that affected field types.

To update fields in a specific part of the document use Aspose.Words.Range.UpdateFields.

UpdateListLabels()

Updates list labels for all list items in the document.

public void UpdateListLabels()

Examples

Shows how to extract the list labels of all paragraphs that are list items.

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

                                                                                      NodeCollection paras = doc.GetChildNodes(NodeType.Paragraph, true);

                                                                                      // Find if we have the paragraph list. In our document, our list uses plain Arabic numbers,
                                                                                      // which start at three and ends at six.
                                                                                      foreach (Paragraph paragraph in paras.OfType<Paragraph>().Where(p => p.ListFormat.IsListItem).ToList())
                                                                                      {
                                                                                          Console.WriteLine($"List item paragraph #{paras.IndexOf(paragraph)}");

                                                                                          // This is the text we get when getting when we output this node to text format.
                                                                                          // This text output will omit list labels. Trim any paragraph formatting characters. 
                                                                                          string paragraphText = paragraph.ToString(SaveFormat.Text).Trim();
                                                                                          Console.WriteLine($"\tExported Text: {paragraphText}");

                                                                                          ListLabel label = paragraph.ListLabel;

                                                                                          // This gets the position of the paragraph in the current level of the list. If we have a list with multiple levels,
                                                                                          // this will tell us what position it is on that level.
                                                                                          Console.WriteLine($"\tNumerical Id: {label.LabelValue}");

                                                                                          // Combine them together to include the list label with the text in the output.
                                                                                          Console.WriteLine($"\tList label combined with text: {label.LabelString} {paragraphText}");
                                                                                      }

Remarks

This method updates list label properties such as Aspose.Words.Lists.ListLabel.LabelValue and Aspose.Words.Lists.ListLabel.LabelString for each Aspose.Words.Paragraph.ListLabel object in the document.

Also, this method is sometimes implicitly called when updating fields in the document. This is required because some fields that may reference list numbers (such as TOC or REF) need them be up-to-date.

UpdatePageLayout()

Rebuilds the page layout of the document.

public void UpdatePageLayout()

Examples

Shows when to recalculate the page layout of the document.

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

                                                                     // Saving a document to PDF, to an image, or printing for the first time will automatically
                                                                     // cache the layout of the document within its pages.
                                                                     doc.Save(ArtifactsDir + "Document.UpdatePageLayout.1.pdf");

                                                                     // Modify the document in some way.
                                                                     doc.Styles["Normal"].Font.Size = 6;
                                                                     doc.Sections[0].PageSetup.Orientation = Aspose.Words.Orientation.Landscape;
                                                                     doc.Sections[0].PageSetup.Margins = Margins.Mirrored;

                                                                     // In the current version of Aspose.Words, modifying the document does not automatically rebuild
                                                                     // the cached page layout. If we wish for the cached layout
                                                                     // to stay up to date, we will need to update it manually.
                                                                     doc.UpdatePageLayout();

                                                                     doc.Save(ArtifactsDir + "Document.UpdatePageLayout.2.pdf");

Remarks

This method formats a document into pages and updates the page number related fields in the document such as PAGE, PAGES, PAGEREF and REF. The up-to-date page layout information is required for a correct rendering of the document to fixed-page formats.

This method is automatically invoked when you first convert a document to PDF, XPS, image or print it. However, if you modify the document after rendering and then attempt to render it again - Aspose.Words will not update the page layout automatically. In this case you should call Aspose.Words.Document.UpdatePageLayout before rendering again.

UpdateTableLayout()

Implements an earlier approach to table column widths re-calculation that has known issues.

[Obsolete("Obsolete, column widths are re-calculated automatically before saving.")]
public void UpdateTableLayout()

Remarks

The method is deprecated and it will be removed in a few releases.

UpdateThumbnail(ThumbnailGeneratingOptions)

Updates Aspose.Words.Properties.BuiltInDocumentProperties.Thumbnail of the document according to the specified options.

public void UpdateThumbnail(ThumbnailGeneratingOptions options)

Parameters

options ThumbnailGeneratingOptions

The generating options to use.

Examples

Shows how to update a document’s thumbnail.

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

                                                      builder.Writeln("Hello world!");
                                                      builder.InsertImage(ImageDir + "Logo.jpg");

                                                      // There are two ways of setting a thumbnail image when saving a document to .epub.
                                                      // 1 -  Use the document's first page:
                                                      doc.UpdateThumbnail();
                                                      doc.Save(ArtifactsDir + "Document.UpdateThumbnail.FirstPage.epub");

                                                      // 2 -  Use the first image found in the document:
                                                      ThumbnailGeneratingOptions options = new ThumbnailGeneratingOptions();
                                                      options.ThumbnailSize = new Size(400, 400);
                                                      options.GenerateFromFirstPage = false;

                                                      doc.UpdateThumbnail(options);
                                                      doc.Save(ArtifactsDir + "Document.UpdateThumbnail.FirstImage.epub");

Remarks

The Aspose.Words.Rendering.ThumbnailGeneratingOptions allows you to specify the source of thumbnail, size and other options. If attempt to generate thumbnail fails, doesn’t change one.

UpdateThumbnail()

Updates Aspose.Words.Properties.BuiltInDocumentProperties.Thumbnail of the document using default options.

public void UpdateThumbnail()

Examples

Shows how to update a document’s thumbnail.

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

                                                      builder.Writeln("Hello world!");
                                                      builder.InsertImage(ImageDir + "Logo.jpg");

                                                      // There are two ways of setting a thumbnail image when saving a document to .epub.
                                                      // 1 -  Use the document's first page:
                                                      doc.UpdateThumbnail();
                                                      doc.Save(ArtifactsDir + "Document.UpdateThumbnail.FirstPage.epub");

                                                      // 2 -  Use the first image found in the document:
                                                      ThumbnailGeneratingOptions options = new ThumbnailGeneratingOptions();
                                                      options.ThumbnailSize = new Size(400, 400);
                                                      options.GenerateFromFirstPage = false;

                                                      doc.UpdateThumbnail(options);
                                                      doc.Save(ArtifactsDir + "Document.UpdateThumbnail.FirstImage.epub");

UpdateWordCount()

Updates word count properties of the document.

public void UpdateWordCount()

Examples

Shows how to update all list labels in a document.

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

                                                             builder.Writeln("Lorem ipsum dolor sit amet, consectetur adipiscing elit, " +
                                                                             "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
                                                             builder.Write("Ut enim ad minim veniam, " +
                                                                             "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.");

                                                             // Aspose.Words does not track document metrics like these in real time.
                                                             Assert.That(doc.BuiltInDocumentProperties.Characters, Is.EqualTo(0));
                                                             Assert.That(doc.BuiltInDocumentProperties.Words, Is.EqualTo(0));
                                                             Assert.That(doc.BuiltInDocumentProperties.Paragraphs, Is.EqualTo(1));
                                                             Assert.That(doc.BuiltInDocumentProperties.Lines, Is.EqualTo(1));

                                                             // To get accurate values for three of these properties, we will need to update them manually.
                                                             doc.UpdateWordCount();

                                                             Assert.That(doc.BuiltInDocumentProperties.Characters, Is.EqualTo(196));
                                                             Assert.That(doc.BuiltInDocumentProperties.Words, Is.EqualTo(36));
                                                             Assert.That(doc.BuiltInDocumentProperties.Paragraphs, Is.EqualTo(2));

                                                             // For the line count, we will need to call a specific overload of the updating method.
                                                             Assert.That(doc.BuiltInDocumentProperties.Lines, Is.EqualTo(1));

                                                             doc.UpdateWordCount(true);

                                                             Assert.That(doc.BuiltInDocumentProperties.Lines, Is.EqualTo(4));

Remarks

Aspose.Words.Document.UpdateWordCount recalculates and updates Characters, Words and Paragraphs properties in the Aspose.Words.Document.BuiltInDocumentProperties collection of the Aspose.Words.Document.

Note that Aspose.Words.Document.UpdateWordCount does not update number of lines and pages properties. Use the Aspose.Words.Document.UpdateWordCount overload and pass true value as a parameter to do that.

When you use an evaluation version, the evaluation watermark will also be included in the word count.

UpdateWordCount(bool)

Updates word count properties of the document, optionally updates Aspose.Words.Properties.BuiltInDocumentProperties.Lines property.

public void UpdateWordCount(bool updateLinesCount)

Parameters

updateLinesCount bool

true if number of lines in the document shall be calculated.

Examples

Shows how to update all list labels in a document.

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

                                                             builder.Writeln("Lorem ipsum dolor sit amet, consectetur adipiscing elit, " +
                                                                             "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
                                                             builder.Write("Ut enim ad minim veniam, " +
                                                                             "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.");

                                                             // Aspose.Words does not track document metrics like these in real time.
                                                             Assert.That(doc.BuiltInDocumentProperties.Characters, Is.EqualTo(0));
                                                             Assert.That(doc.BuiltInDocumentProperties.Words, Is.EqualTo(0));
                                                             Assert.That(doc.BuiltInDocumentProperties.Paragraphs, Is.EqualTo(1));
                                                             Assert.That(doc.BuiltInDocumentProperties.Lines, Is.EqualTo(1));

                                                             // To get accurate values for three of these properties, we will need to update them manually.
                                                             doc.UpdateWordCount();

                                                             Assert.That(doc.BuiltInDocumentProperties.Characters, Is.EqualTo(196));
                                                             Assert.That(doc.BuiltInDocumentProperties.Words, Is.EqualTo(36));
                                                             Assert.That(doc.BuiltInDocumentProperties.Paragraphs, Is.EqualTo(2));

                                                             // For the line count, we will need to call a specific overload of the updating method.
                                                             Assert.That(doc.BuiltInDocumentProperties.Lines, Is.EqualTo(1));

                                                             doc.UpdateWordCount(true);

                                                             Assert.That(doc.BuiltInDocumentProperties.Lines, Is.EqualTo(4));

Remarks

This method will rebuild page layout of the document.

 English