Document class

Document class

Represents a Word document. To learn more, visit the Working with Document documentation article.

Remarks

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

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

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

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.

Document stores document-wide information such as DocumentBase.styles, Document.builtInDocumentProperties, Document.customDocumentProperties, lists and macros. Most of these objects are accessible via the corresponding properties of the Document.

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

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

The Document can contain only Section objects.

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

Inheritance: DocumentDocumentBaseCompositeNodeNode

Constructors

NameDescription
Document()Creates a blank Word document.
Document(fileName)Opens an existing document from a file. Automatically detects the file format.
Document(fileName, loadOptions)Opens an existing document from a file. Allows to specify additional options such as an encryption password.
Document(stream)Opens an existing document from a stream. Automatically detects the file format.
Document(stream, loadOptions)Opens an existing document from a stream. Allows to specify additional options such as an encryption password.

Properties

NameDescription
attachedTemplateGets or sets the full path of the template attached to the document.
automaticallyUpdateStylesGets 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.
backgroundShapeGets or sets the background shape of the document. Can be null.
(Inherited from DocumentBase)
bibliographyGets the Document.bibliography object that represents the list of sources available in the document.
builtInDocumentPropertiesReturns a collection that represents all the built-in document properties of the document.
compatibilityOptionsProvides access to document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).
complianceGets the OOXML compliance version determined from the loaded document content. Makes sense only for OOXML documents.
countGets the number of immediate children of this node.
(Inherited from CompositeNode)
customDocumentPropertiesReturns a collection that represents all the custom document properties of the document.
customNodeIdSpecifies custom node identifier.
(Inherited from Node)
customXmlPartsGets or sets the collection of Custom XML Data Storage Parts.
defaultTabStopGets or sets the interval (in points) between the default tab stops.
digitalSignaturesGets the collection of digital signatures for this document and their validation results.
documentGets the document to which this node belongs.
(Inherited from Node)
endnoteOptionsProvides options that control numbering and positioning of endnotes in this document.
fieldOptionsGets a FieldOptions object that represents options to control field handling in the document.
firstChildGets the first child of the node.
(Inherited from CompositeNode)
firstSectionGets the first section in the document.
fontInfosProvides access to properties of fonts used in this document.
(Inherited from DocumentBase)
fontSettingsGets or sets document font settings.
footnoteOptionsProvides options that control numbering and positioning of footnotes in this document.
footnoteSeparatorsProvides access to the footnote/endnote separators defined in the document.
(Inherited from DocumentBase)
framesetReturns a Document.frameset instance if this document represents a frames page.
glossaryDocumentGets 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.
grammarCheckedReturns true if the document has been checked for grammar.
hasChildNodesReturns true if this node has any child nodes.
(Inherited from CompositeNode)
hasMacrosReturns true if the document has a VBA project (macros).
hasRevisionsReturns true if the document has any tracked changes.
hyphenationOptionsProvides access to document hyphenation options.
includeTextboxesFootnotesEndnotesInStatSpecifies whether to include textboxes, footnotes and endnotes in word count statistics.
isCompositeReturns true if this node can contain other nodes.
(Inherited from Node)
justificationModeGets or sets the character spacing adjustment of a document.
lastChildGets the last child of the node.
(Inherited from CompositeNode)
lastSectionGets the last section in the document.
layoutOptionsGets a LayoutOptions object that represents options to control the layout process of this document.
listsProvides access to the list formatting used in the document.
(Inherited from DocumentBase)
mailMergeSettingsGets or sets the object that contains all of the mail merge information for a document.
nextSiblingGets the node immediately following this node.
(Inherited from Node)
nodeChangingCallbackCalled when a node is inserted or removed in the document.
(Inherited from DocumentBase)
nodeTypeReturns NodeType.Document.
originalFileNameGets the original file name of the document.
originalLoadFormatGets the format of the original document that was loaded into this object.
packageCustomPartsGets or sets the collection of custom parts (arbitrary content) that are linked to the OOXML package using “unknown relationships”.
pageColorGets or sets the page color of the document. This property is a simpler version of DocumentBase.backgroundShape.
(Inherited from DocumentBase)
pageCountGets the number of pages in the document as calculated by the most recent page layout operation.
parentNodeGets the immediate parent of this node.
(Inherited from Node)
previousSiblingGets the node immediately preceding this node.
(Inherited from Node)
protectionTypeGets the currently active document protection type.
punctuationKerningSpecifies whether kerning applies to both Latin text and punctuation.
rangeReturns a Range object that represents the portion of a document that is contained in this node.
(Inherited from Node)
removePersonalInformationGets or sets a flag indicating that Microsoft Word will remove all user information from comments, revisions and document properties upon saving the document.
resourceLoadingCallbackAllows to control how external resources are loaded.
(Inherited from DocumentBase)
revisionsGets a collection of revisions (tracked changes) that exist in this document.
revisionsViewGets or sets a value indicating whether to work with the original or revised version of a document.
sectionsReturns a collection that represents all sections in the document.
shadeFormDataSpecifies whether to turn on the gray shading on form fields.
showGrammaticalErrorsSpecifies whether to display grammar errors in this document.
showSpellingErrorsSpecifies whether to display spelling errors in this document.
spellingCheckedReturns true if the document has been checked for spelling.
stylesReturns a collection of styles defined in the document.
(Inherited from DocumentBase)
themeGets the Document.theme object for this document.
trackRevisionsTrue if changes are tracked when this document is edited in Microsoft Word.
variablesReturns the collection of variables added to a document or template.
vbaProjectGets or sets a Document.vbaProject.
versionsCountGets the number of document versions that was stored in the DOC document.
viewOptionsProvides options to control how the document is displayed in Microsoft Word.
watermarkProvides access to the document watermark.
webExtensionTaskPanesReturns a collection that represents a list of task pane add-ins.
writeProtectionProvides access to the document write protection options.

Methods

NameDescription
acceptAllRevisions()Accepts all tracked changes in the document.
appendChild(newChild)Adds the specified node to the end of the list of child nodes for this node.
(Inherited from CompositeNode)
appendDocument(srcDoc, importFormatMode)Appends the specified document to the end of this document.
appendDocument(srcDoc, importFormatMode, importFormatOptions)Appends the specified document to the end of this document.
asBody()Cast node to Body.
(Inherited from Node)
asBookmarkEnd()Cast node to BookmarkEnd.
(Inherited from Node)
asBookmarkStart()Cast node to BookmarkStart.
(Inherited from Node)
asBuildingBlock()Cast node to BuildingBlock.
(Inherited from Node)
asCell()Cast node to Cell.
(Inherited from Node)
asComment()Cast node to Comment.
(Inherited from Node)
asCommentRangeEnd()Cast node to CommentRangeEnd.
(Inherited from Node)
asCommentRangeStart()Cast node to CommentRangeStart.
(Inherited from Node)
asCompositeNode()Cast node to CompositeNode.
(Inherited from Node)
asDocument()Cast node to Node.document.
(Inherited from Node)
asEditableRangeEnd()Cast node to EditableRangeEnd.
(Inherited from Node)
asEditableRangeStart()Cast node to EditableRangeStart.
(Inherited from Node)
asFieldEnd()Cast node to FieldEnd.
(Inherited from Node)
asFieldSeparator()Cast node to FieldSeparator.
(Inherited from Node)
asFieldStart()Cast node to FieldStart.
(Inherited from Node)
asFootnote()Cast node to Footnote.
(Inherited from Node)
asFormField()Cast node to FormField.
(Inherited from Node)
asGlossaryDocument()Cast node to GlossaryDocument.
(Inherited from Node)
asGroupShape()Cast node to GroupShape.
(Inherited from Node)
asHeaderFooter()Cast node to HeaderFooter.
(Inherited from Node)
asOfficeMath()Cast node to OfficeMath.
(Inherited from Node)
asParagraph()Cast node to Paragraph.
(Inherited from Node)
asRow()Cast node to Row.
(Inherited from Node)
asRun()Cast node to Run.
(Inherited from Node)
asSection()Cast node to Section.
(Inherited from Node)
asShape()Cast node to Shape.
(Inherited from Node)
asSmartTag()Cast node to SmartTag.
(Inherited from Node)
asSpecialChar()Cast node to SpecialChar.
(Inherited from Node)
asStructuredDocumentTag()Cast node to StructuredDocumentTag.
(Inherited from Node)
asStructuredDocumentTagRangeEnd()Cast node to StructuredDocumentTagRangeEnd.
(Inherited from Node)
asStructuredDocumentTagRangeStart()Cast node to StructuredDocumentTagRangeStart.
(Inherited from Node)
asSubDocument()Cast node to SubDocument.
(Inherited from Node)
asTable()Cast node to Table.
(Inherited from Node)
cleanup()Cleans unused styles and lists from the document.
cleanup(options)Cleans unused styles and lists from the document depending on given CleanupOptions.
clone()Performs a deep copy of the Document.
compare(document, author, dateTime)Compares this document with another document producing changes as number of edit and format revisions Revision.
compare(document, author, dateTime, options)Compares this document with another document producing changes as a number of edit and format revisions Revision. Allows to specify comparison options using CompareOptions.
copyStylesFromTemplate(template)Copies styles from the specified template to a document.
copyStylesFromTemplate(template)Copies styles from the specified template to a document.
ensureMinimum()If the document contains no sections, creates one section with one paragraph.
expandTableStylesToDirectFormatting()Converts formatting specified in table styles into direct formatting on tables in the document.
extractPages(index, count)Returns the Document object representing specified range of pages.
getAncestor(ancestorType)Gets the first ancestor of the specified NodeType.
(Inherited from Node)
getBuildingBlock(index, isDeep)Returns an Nth child BuildingBlock node.
(Inherited from CompositeNode)
getChild(nodeType, index, isDeep)Returns an Nth child node that matches the specified type.
(Inherited from CompositeNode)
getChildNodes(nodeType, isDeep)Returns a live collection of child nodes that match the specified type.
(Inherited from CompositeNode)
getComment(index, isDeep)Returns an Nth child Comment node.
(Inherited from CompositeNode)
getEditableRangeStart(index, isDeep)Returns an Nth child EditableRangeStart node.
(Inherited from CompositeNode)
getFootnote(index, isDeep)Returns an Nth child Footnote node.
(Inherited from CompositeNode)
getGroupShape(index, isDeep)Returns an Nth child GroupShape node.
(Inherited from CompositeNode)
getOfficeMath(index, isDeep)Returns an Nth child OfficeMath node.
(Inherited from CompositeNode)
getPageInfo(pageIndex)Gets the page size, orientation and other information about a page that might be useful for printing or rendering.
getParagraph(index, isDeep)Returns an Nth child Paragraph node.
(Inherited from CompositeNode)
getRun(index, isDeep)Returns an Nth child Run node.
(Inherited from CompositeNode)
getSdt(index, isDeep)Returns an Nth child StructuredDocumentTag node.
(Inherited from CompositeNode)
getSdtRangeEnd(index, isDeep)Returns an Nth child StructuredDocumentTagRangeEnd node.
(Inherited from CompositeNode)
getSdtRangeStart(index, isDeep)Returns an Nth child StructuredDocumentTagRangeStart node.
(Inherited from CompositeNode)
getShape(index, isDeep)Returns an Nth child Shape node.
(Inherited from CompositeNode)
getSmartTag(index, isDeep)Returns an Nth child SmartTag node.
(Inherited from CompositeNode)
getTable(index, isDeep)Returns an Nth child Table node.
(Inherited from CompositeNode)
getText()Gets the text of this node and of all its children.
(Inherited from Node)
importNode(srcNode, isImportChildren)Imports a node from another document to the current document.
(Inherited from DocumentBase)
importNode(srcNode, isImportChildren, importFormatMode)Imports a node from another document to the current document with an option to control formatting.
(Inherited from DocumentBase)
indexOf(child)Returns the index of the specified child node in the child node array.
(Inherited from CompositeNode)
insertAfter(newChild, refChild)Inserts the specified node immediately after the specified reference node.
(Inherited from CompositeNode)
insertBefore(newChild, refChild)Inserts the specified node immediately before the specified reference node.
(Inherited from CompositeNode)
joinRunsWithSameFormatting()Joins runs with same formatting in all paragraphs of the document.
nextPreOrder(rootNode)Gets next node according to the pre-order tree traversal algorithm.
(Inherited from Node)
nodeTypeToString(nodeType)A utility method that converts a node type enum value into a user friendly string.
(Inherited from Node)
normalizeFieldTypes()Changes field type values FieldChar.fieldType of FieldStart, FieldSeparator, FieldEnd in the whole document so that they correspond to the field types contained in the field codes.
prependChild(newChild)Adds the specified node to the beginning of the list of child nodes for this node.
(Inherited from CompositeNode)
previousPreOrder(rootNode)Gets the previous node according to the pre-order tree traversal algorithm.
(Inherited from Node)
protect(type)Protects the document from changes without changing the existing password or assigns a random password.
protect(type, password)Protects the document from changes and optionally sets a protection password.
referenceEquals(other)
(Inherited from Node)
remove()Removes itself from the parent.
(Inherited from Node)
removeAllChildren()Removes all the child nodes of the current node.
(Inherited from CompositeNode)
removeBlankPages()Removes blank pages from the document.
removeChild(oldChild)Removes the specified child node.
(Inherited from CompositeNode)
removeExternalSchemaReferences()Removes external XML schema references from this document.
removeMacros()Removes all macros (the VBA project) as well as toolbars and command customizations from the document.
removeSmartTags()Removes all SmartTag descendant nodes of the current node.
(Inherited from CompositeNode)
save(stream, saveFormat)Saves the document to a stream using the specified format.
save(stream, saveOptions)Saves the document to a stream using the specified save options.
save(fileName)Saves the document to a file. Automatically determines the save format from the extension.
save(fileName, saveFormat)Saves the document to a file in the specified format.
save(fileName, saveOptions)Saves the document to a file using the specified save options.
selectNodes(xpath)Selects a list of nodes matching the XPath expression.
(Inherited from CompositeNode)
selectSingleNode(xpath)Selects the first Node that matches the XPath expression.
(Inherited from CompositeNode)
startTrackRevisions(author, dateTime)Starts automatically marking all further changes you make to the document programmatically as revision changes.
startTrackRevisions(author)Starts automatically marking all further changes you make to the document programmatically as revision changes.
stopTrackRevisions()Stops automatic marking of document changes as revisions.
toString(saveFormat)Exports the content of the node into a string in the specified format.
(Inherited from Node)
toString(saveOptions)Exports the content of the node into a string using the specified save options.
(Inherited from Node)
unlinkFields()Unlinks fields in the whole document.
unprotect()Removes protection from the document regardless of the password.
unprotect(password)Removes protection from the document if a correct password is specified.
updateActualReferenceMarks()Updates the Footnote.actualReferenceMark property of all footnotes and endnotes in the document.
updateFields()Updates the values of fields in the whole document.
updateListLabels()Updates list labels for all list items in the document.
updatePageLayout()Rebuilds the page layout of the document.
updateThumbnail(options)Updates BuiltInDocumentProperties.thumbnail of the document according to the specified options.
updateThumbnail()Updates BuiltInDocumentProperties.thumbnail of the document using default options.
updateWordCount()Updates word count properties of the document.
updateWordCount(updateLinesCount)Updates word count properties of the document, optionally updates BuiltInDocumentProperties.lines property.

Examples

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

test('ExecuteDataTable', () => {
  let 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:
  let doc = CreateSourceDocExecuteDataTable();

  doc.mailMerge.execute(table);

  doc.save(base.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.at(1));

  doc.save(base.artifactsDir + "MailMerge.ExecuteDataTable.OneRow.docx");
});


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

  builder.insertField(" MERGEFIELD CustomerName ");
  builder.insertParagraph();
  builder.insertField(" MERGEFIELD Address ");

  return doc;
}

See Also