Aspose::Words::Document Class Reference

Detailed Description

Represents a Word document.

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

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

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

To draw document pages directly onto a Graphics object use RenderToScale() or RenderToSize() method.

To print the document, use one of the Print() methods.

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

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

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

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

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

The Document can contain only Section objects.

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

#include <Aspose.Words.Cpp/Document.h>

+ Inheritance diagram for Aspose::Words::Document:

Public Member Functions

 Document ()
 Creates a blank Word document. More...
 
 Document (const SharedPtr< Stream > &stream)
 Opens an existing document from a stream. Automatically detects the file format. More...
 
 Document (const SharedPtr< Stream > &stream, const SharedPtr< LoadOptions > &loadOptions)
 Opens an existing document from a stream. Allows to specify additional options such as an encryption password. More...
 
 Document (const String &fileName)
 Opens an existing document from a file. Automatically detects the file format. More...
 
 Document (const String &fileName, const SharedPtr< LoadOptions > &loadOptions)
 Opens an existing document from a file. Allows to specify additional options such as an encryption password. More...
 
template<typename CharType , typename Traits >
 Document (std::basic_istream< CharType, Traits > &stream, SharedPtr< LoadOptions > loadOptions)
 
bool Accept (SharedPtr< DocumentVisitor > visitor) override
 Accepts a visitor. More...
 
void AcceptAllRevisions ()
 Accepts all tracked changes in the document. More...
 
void AppendDocument (const SharedPtr< Document > &srcDoc, ImportFormatMode importFormatMode)
 Appends the specified document to the end of this document. More...
 
void AppendDocument (const SharedPtr< Document > &srcDoc, ImportFormatMode importFormatMode, const SharedPtr< ImportFormatOptions > &importFormatOptions)
 Appends the specified document to the end of this document. More...
 
void Cleanup ()
 Cleans unused styles and lists from the document. More...
 
void Cleanup (const SharedPtr< CleanupOptions > &options)
 Cleans unused styles and lists from the document depending on given CleanupOptions. More...
 
SharedPtr< DocumentClone ()
 Performs a deep copy of the Document. More...
 
void Compare (const SharedPtr< Document > &document, const String &author, DateTime dateTime)
 Compares this document with another document producing changes as number of edit and format revisions Revision. More...
 
void Compare (const SharedPtr< Document > &document, const String &author, DateTime dateTime, const SharedPtr< CompareOptions > &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. More...
 
void CopyStylesFromTemplate (const SharedPtr< Document > &template_)
 Copies styles from the specified template to a document. More...
 
void CopyStylesFromTemplate (const String &template_)
 Copies styles from the specified template to a document. More...
 
void EnsureMinimum ()
 If the document contains no sections, creates one section with one paragraph. More...
 
void ExpandTableStylesToDirectFormatting ()
 Converts formatting specified in table styles into direct formatting on tables in the document. More...
 
SharedPtr< DocumentExtractPages (int32_t index, int32_t count)
 Returns the Document object representing specified range of pages. More...
 
String get_AttachedTemplate ()
 Gets or sets the full path of the template attached to the document. More...
 
bool get_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. More...
 
SharedPtr< BuiltInDocumentPropertiesget_BuiltInDocumentProperties () const
 Returns a collection that represents all the built-in document properties of the document. More...
 
SharedPtr< CompatibilityOptionsget_CompatibilityOptions ()
 Provides access to document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word). More...
 
OoxmlCompliance get_Compliance ()
 Gets the OOXML compliance version determined from the loaded document content. Makes sense only for OOXML documents. More...
 
SharedPtr< CustomDocumentPropertiesget_CustomDocumentProperties ()
 Returns a collection that represents all the custom document properties of the document. More...
 
SharedPtr< CustomXmlPartCollectionget_CustomXmlParts () const
 Gets or sets the collection of Custom XML Data Storage Parts. More...
 
double get_DefaultTabStop ()
 Gets or sets the interval (in points) between the default tab stops. More...
 
SharedPtr< DigitalSignatureCollectionget_DigitalSignatures () const
 Gets the collection of digital signatures for this document and their validation results. More...
 
SharedPtr< EndnoteOptionsget_EndnoteOptions ()
 Provides options that control numbering and positioning of endnotes in this document. More...
 
SharedPtr< FieldOptionsget_FieldOptions ()
 Gets a FieldOptions object that represents options to control field handling in the document. More...
 
SharedPtr< Sectionget_FirstSection ()
 Gets the first section in the document. More...
 
SharedPtr< FontSettingsget_FontSettings () const
 Gets or sets document font settings. More...
 
SharedPtr< FootnoteOptionsget_FootnoteOptions ()
 Provides options that control numbering and positioning of footnotes in this document. More...
 
SharedPtr< Framesetget_Frameset () const
 Returns a Frameset instance if this document represents a frames page. More...
 
SharedPtr< GlossaryDocumentget_GlossaryDocument () const
 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. More...
 
bool get_GrammarChecked ()
 Returns true if the document has been checked for grammar. More...
 
bool get_HasMacros ()
 Returns true if the document has a VBA project (macros). More...
 
bool get_HasRevisions ()
 Returns true if the document has any tracked changes. More...
 
SharedPtr< HyphenationOptionsget_HyphenationOptions ()
 Provides access to document hyphenation options. More...
 
SharedPtr< Sectionget_LastSection ()
 Gets the last section in the document. More...
 
SharedPtr< LayoutOptionsget_LayoutOptions () const
 Gets a LayoutOptions object that represents options to control the layout process of this document. More...
 
SharedPtr< MailMergeget_MailMerge ()
 Returns a MailMerge object that represents the mail merge functionality for the document. More...
 
SharedPtr< MailMergeSettingsget_MailMergeSettings ()
 Gets or sets the object that contains all of the mail merge information for a document. More...
 
NodeType get_NodeType () const override
 Returns NodeType.Document. More...
 
String get_OriginalFileName () const
 Gets the original file name of the document. More...
 
LoadFormat get_OriginalLoadFormat () const
 Gets the format of the original document that was loaded into this object. More...
 
SharedPtr< CustomPartCollectionget_PackageCustomParts () const
 Gets or sets the collection of custom parts (arbitrary content) that are linked to the OOXML package using "unknown relationships". More...
 
int32_t get_PageCount ()
 Gets the number of pages in the document as calculated by the most recent page layout operation. More...
 
ProtectionType get_ProtectionType ()
 Gets the currently active document protection type. More...
 
bool get_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. More...
 
SharedPtr< RevisionCollectionget_Revisions ()
 Gets a collection of revisions (tracked changes) that exist in this document. More...
 
RevisionsView get_RevisionsView () const
 Gets or sets a value indicating whether to work with the original or revised version of a document. More...
 
SharedPtr< SectionCollectionget_Sections ()
 Returns a collection that represents all sections in the document. More...
 
bool get_ShadeFormData ()
 Specifies whether to turn on the gray shading on form fields. More...
 
bool get_ShowGrammaticalErrors ()
 Specifies whether to display grammar errors in this document. More...
 
bool get_ShowSpellingErrors ()
 Specifies whether to display spelling errors in this document. More...
 
bool get_SpellingChecked ()
 Returns true if the document has been checked for spelling. More...
 
SharedPtr< Themeget_Theme ()
 Gets the Theme object for this document. More...
 
bool get_TrackRevisions ()
 True if changes are tracked when this document is edited in Microsoft Word. More...
 
SharedPtr< VariableCollectionget_Variables ()
 Returns the collection of variables added to a document or template. More...
 
SharedPtr< VbaProjectget_VbaProject () const
 Gets or sets a VbaProject. More...
 
int32_t get_VersionsCount ()
 Gets the number of document versions that was stored in the DOC document. More...
 
SharedPtr< ViewOptionsget_ViewOptions ()
 Provides options to control how the document is displayed in Microsoft Word. More...
 
SharedPtr< Watermarkget_Watermark ()
 Provides access to the document watermark. More...
 
SharedPtr< TaskPaneCollectionget_WebExtensionTaskPanes () const
 Returns a collection that represents a list of task pane add-ins. More...
 
SharedPtr< WriteProtectionget_WriteProtection ()
 Provides access to the document write protection options. More...
 
SharedPtr< PageInfoGetPageInfo (int32_t pageIndex)
 Gets the page size, orientation and other information about a page that might be useful for printing or rendering. More...
 
virtual const TypeInfoGetType () const override
 
virtual bool Is (const TypeInfo &target) const override
 
int32_t JoinRunsWithSameFormatting ()
 Joins runs with same formatting in all paragraphs of the document. More...
 
void NormalizeFieldTypes ()
 Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in the whole document so that they correspond to the field types contained in the field codes. More...
 
void Protect (ProtectionType type)
 Protects the document from changes without changing the existing password or assigns a random password. More...
 
void Protect (ProtectionType type, const String &password)
 Protects the document from changes and optionally sets a protection password. More...
 
void RemoveExternalSchemaReferences ()
 Removes external XML schema references from this document. More...
 
void RemoveMacros ()
 Removes all macros (the VBA project) as well as toolbars and command customizations from the document. More...
 
SizeF RenderToScale (int32_t pageIndex, const SharedPtr< Graphics > &graphics, float x, float y, float scale)
 Renders a document page into a object to a specified scale. More...
 
float RenderToSize (int32_t pageIndex, const SharedPtr< Graphics > &graphics, float x, float y, float width, float height)
 Renders a document page into a object to a specified size. More...
 
SharedPtr< SaveOutputParametersSave (const SharedPtr< Stream > &stream, SaveFormat saveFormat)
 Saves the document to a stream using the specified format. More...
 
SharedPtr< SaveOutputParametersSave (const SharedPtr< Stream > &stream, const SharedPtr< SaveOptions > &saveOptions)
 Saves the document to a stream using the specified save options. More...
 
SharedPtr< SaveOutputParametersSave (const String &fileName)
 Saves the document to a file. Automatically determines the save format from the extension. More...
 
SharedPtr< SaveOutputParametersSave (const String &fileName, SaveFormat saveFormat)
 Saves the document to a file in the specified format. More...
 
SharedPtr< SaveOutputParametersSave (const String &fileName, const SharedPtr< SaveOptions > &saveOptions)
 Saves the document to a file using the specified save options. More...
 
template<typename CharType , typename Traits >
SharedPtr< SaveOutputParametersSave (std::basic_ostream< CharType, Traits > &stream, SaveFormat saveFormat)
 
template<typename CharType , typename Traits >
SharedPtr< SaveOutputParametersSave (std::basic_ostream< CharType, Traits > &stream, SharedPtr< SaveOptions > saveOptions)
 
void set_AttachedTemplate (const String &value)
 Setter for get_AttachedTemplate. More...
 
void set_AutomaticallyUpdateStyles (bool value)
 Setter for get_AutomaticallyUpdateStyles. More...
 
void set_CustomXmlParts (const SharedPtr< CustomXmlPartCollection > &value)
 Setter for get_CustomXmlParts. More...
 
void set_DefaultTabStop (double value)
 Setter for get_DefaultTabStop. More...
 
void set_FontSettings (const SharedPtr< FontSettings > &value)
 Setter for get_FontSettings. More...
 
void set_GlossaryDocument (const SharedPtr< GlossaryDocument > &value)
 Setter for get_GlossaryDocument. More...
 
void set_GrammarChecked (bool value)
 Setter for get_GrammarChecked. More...
 
void set_MailMergeSettings (const SharedPtr< MailMergeSettings > &value)
 Setter for get_MailMergeSettings. More...
 
void set_PackageCustomParts (const SharedPtr< CustomPartCollection > &value)
 Setter for get_PackageCustomParts. More...
 
void set_RemovePersonalInformation (bool value)
 Setter for get_RemovePersonalInformation. More...
 
void set_RevisionsView (RevisionsView value)
 Setter for get_RevisionsView. More...
 
void set_ShadeFormData (bool value)
 Setter for get_ShadeFormData. More...
 
void set_ShowGrammaticalErrors (bool value)
 Setter for get_ShowGrammaticalErrors. More...
 
void set_ShowSpellingErrors (bool value)
 Setter for get_ShowSpellingErrors. More...
 
void set_SpellingChecked (bool value)
 Setter for get_SpellingChecked. More...
 
void set_TrackRevisions (bool value)
 Setter for get_TrackRevisions. More...
 
void set_VbaProject (const SharedPtr< VbaProject > &value)
 Setter for get_VbaProject. More...
 
void StartTrackRevisions (const String &author)
 Starts automatically marking all further changes you make to the document programmatically as revision changes. More...
 
void StartTrackRevisions (const String &author, DateTime dateTime)
 Starts automatically marking all further changes you make to the document programmatically as revision changes. More...
 
void StopTrackRevisions ()
 Stops automatic marking of document changes as revisions. More...
 
void UnlinkFields ()
 Unlinks fields in the whole document. More...
 
void Unprotect ()
 Removes protection from the document regardless of the password. More...
 
bool Unprotect (const String &password)
 Removes protection from the document if a correct password is specified. More...
 
void UpdateFields ()
 Updates the values of fields in the whole document. More...
 
void UpdateListLabels ()
 Updates list labels for all list items in the document. More...
 
void UpdatePageLayout ()
 Rebuilds the page layout of the document. More...
 
void UpdateTableLayout ()
 Updates widths of cells and tables in the document according to their preferred widths and content. You do not need to call this method if the tables appear correct in the output document. More...
 
void UpdateThumbnail ()
 Updates Thumbnail of the document using default options. More...
 
void UpdateThumbnail (const SharedPtr< ThumbnailGeneratingOptions > &options)
 Updates Thumbnail of the document according to the specified options. More...
 
void UpdateWordCount ()
 Updates word count properties of the document. More...
 
void UpdateWordCount (bool updateLinesCount)
 Updates word count properties of the document, optionally updates Lines property. More...
 
- Public Member Functions inherited from DocumentBase
SharedPtr< Shapeget_BackgroundShape () const
 Gets or sets the background shape of the document. Can be null. More...
 
SharedPtr< DocumentBaseget_Document () const override
 Gets the document to which this node belongs. More...
 
SharedPtr< FontInfoCollectionget_FontInfos () const
 Provides access to properties of fonts used in this document. More...
 
SharedPtr< ListCollectionget_Lists () const
 Provides access to the list formatting used in the document. More...
 
SharedPtr< INodeChangingCallbackget_NodeChangingCallback ()
 Called when a node is inserted or removed in the document. More...
 
Color get_PageColor ()
 Gets or sets the page color of the document. This property is a simpler version of BackgroundShape. More...
 
SharedPtr< IResourceLoadingCallbackget_ResourceLoadingCallback () const
 Allows to control how external resources are loaded. More...
 
SharedPtr< StyleCollectionget_Styles () const
 Returns a collection of styles defined in the document. More...
 
SharedPtr< IWarningCallbackget_WarningCallback () const
 Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss. More...
 
SharedPtr< NodeImportNode (const SharedPtr< Node > &srcNode, bool isImportChildren)
 Imports a node from another document to the current document. More...
 
SharedPtr< NodeImportNode (const SharedPtr< Node > &srcNode, bool isImportChildren, ImportFormatMode importFormatMode)
 Imports a node from another document to the current document with an option to control formatting. More...
 
void set_BackgroundShape (const SharedPtr< Shape > &value)
 Setter for get_BackgroundShape. More...
 
void set_NodeChangingCallback (const SharedPtr< INodeChangingCallback > &value)
 Setter for get_NodeChangingCallback. More...
 
void set_PageColor (Color value)
 Setter for get_PageColor. More...
 
void set_ResourceLoadingCallback (const SharedPtr< IResourceLoadingCallback > &value)
 Setter for get_ResourceLoadingCallback. More...
 
void set_WarningCallback (const SharedPtr< IWarningCallback > &value)
 Setter for get_WarningCallback. More...
 
- Public Member Functions inherited from CompositeNode
SharedPtr< NodeAppendChild (const SharedPtr< Node > &newChild)
 Adds the specified node to the end of the list of child nodes for this node. More...
 
SharedPtr< NodeCollectionget_ChildNodes ()
 Gets all immediate child nodes of this node. More...
 
int32_t get_Count ()
 Gets the number of immediate children of this node. More...
 
SharedPtr< Nodeget_FirstChild () const
 Gets the first child of the node. More...
 
bool get_HasChildNodes ()
 Returns true if this node has any child nodes. More...
 
bool get_IsComposite () override
 Returns true as this node can have child nodes. More...
 
SharedPtr< Nodeget_LastChild () const
 Gets the last child of the node. More...
 
SharedPtr< NodeGetChild (NodeType nodeType, int32_t index, bool isDeep)
 Returns an Nth child node that matches the specified type. More...
 
SharedPtr< NodeCollectionGetChildNodes (NodeType nodeType, bool isDeep)
 Returns a live collection of child nodes that match the specified type. More...
 
SharedPtr< IEnumerator< SharedPtr< Node > > > GetEnumerator () override
 Provides support for the for each style iteration over the child nodes of this node. More...
 
String GetText () override
 Gets the text of this node and of all its children. More...
 
int32_t IndexOf (const SharedPtr< Node > &child)
 Returns the index of the specified child node in the child node array. More...
 
SharedPtr< NodeInsertAfter (const SharedPtr< Node > &newChild, const SharedPtr< Node > &refChild)
 Inserts the specified node immediately after the specified reference node. More...
 
SharedPtr< NodeInsertBefore (const SharedPtr< Node > &newChild, const SharedPtr< Node > &refChild)
 Inserts the specified node immediately before the specified reference node. More...
 
SharedPtr< NodePrependChild (const SharedPtr< Node > &newChild)
 Adds the specified node to the beginning of the list of child nodes for this node. More...
 
void RemoveAllChildren ()
 Removes all the child nodes of the current node. More...
 
SharedPtr< NodeRemoveChild (const SharedPtr< Node > &oldChild)
 Removes the specified child node. More...
 
void RemoveSmartTags ()
 Removes all SmartTag descendant nodes of the current node. More...
 
SharedPtr< NodeListSelectNodes (const String &xpath)
 Selects a list of nodes matching the XPath expression. More...
 
SharedPtr< NodeSelectSingleNode (const String &xpath)
 Selects the first Node that matches the XPath expression. More...
 
- Public Member Functions inherited from Node
SharedPtr< NodeClone (bool isCloneChildren)
 Creates a duplicate of the node. More...
 
int32_t get_CustomNodeId () const
 Specifies custom node identifier. More...
 
SharedPtr< Nodeget_NextSibling ()
 Gets the node immediately following this node. More...
 
SharedPtr< CompositeNodeget_ParentNode ()
 Gets the immediate parent of this node. More...
 
SharedPtr< Nodeget_PreviousSibling ()
 Gets the node immediately preceding this node. More...
 
SharedPtr< Rangeget_Range ()
 Returns a Range object that represents the portion of a document that is contained in this node. More...
 
SharedPtr< CompositeNodeGetAncestor (NodeType ancestorType)
 Gets the first ancestor of the specified NodeType. More...
 
template<typename T >
GetAncestorOf ()
 
SharedPtr< NodeNextPreOrder (const SharedPtr< Node > &rootNode)
 Gets next node according to the pre-order tree traversal algorithm. More...
 
SharedPtr< NodePreviousPreOrder (const SharedPtr< Node > &rootNode)
 Gets the previous node according to the pre-order tree traversal algorithm. More...
 
void Remove ()
 Removes itself from the parent. More...
 
void set_CustomNodeId (int32_t value)
 Setter for get_CustomNodeId. More...
 
String ToString (SaveFormat saveFormat)
 Exports the content of the node into a string in the specified format. More...
 
String ToString (const SharedPtr< SaveOptions > &saveOptions)
 Exports the content of the node into a string using the specified save options. More...
 

Static Public Member Functions

static const TypeInfoType ()
 
- Static Public Member Functions inherited from DocumentBase
static const TypeInfoType ()
 
- Static Public Member Functions inherited from CompositeNode
static const TypeInfoType ()
 
- Static Public Member Functions inherited from Node
static String NodeTypeToString (NodeType nodeType)
 A utility method that converts a node type enum value into a user friendly string. More...
 
static const TypeInfoType ()
 

Constructor & Destructor Documentation

◆ Document() [1/6]

Aspose::Words::Document::Document ( )

Creates a blank Word document.

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

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

Examples

Shows how to create and load documents.

// There are two ways of creating a Document object using Aspose.Words.
// 1 - Create a blank document:
auto doc = MakeObject<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->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
// 2 - Load a document that exists in the local file system:
doc = MakeObject<Document>(MyDir + u"Document.docx");
// Loaded documents will have contents that we can access and edit.
ASSERT_EQ(u"Hello World!", doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetText().Trim());
// 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 = MakeObject<Document>(MyDir + u"Encrypted.docx", MakeObject<LoadOptions>(u"docPassword"));
ASSERT_EQ(u"Test encrypted document.", doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetText().Trim());

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

auto doc = MakeObject<Document>();
auto run = MakeObject<Run>(doc, u"Hello world!");
SharedPtr<Aspose::Words::Font> font = run->get_Font();
font->set_Name(u"Courier New");
font->set_Size(36);
font->set_HighlightColor(System::Drawing::Color::get_Yellow());
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(run);
doc->Save(ArtifactsDir + u"Font.CreateFormattedRun.docx");

◆ Document() [2/6]

Aspose::Words::Document::Document ( const System::String fileName)

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

Parameters
fileNameFile name of the document to open.
Exceptions
Aspose::Words::UnsupportedFileFormatExceptionThe document format is not recognized or not supported.
Aspose::Words::FileCorruptedExceptionThe document appears to be corrupted and cannot be loaded.
System::ExceptionThere is a problem with the document and it should be reported to Aspose.Words developers.
System::IO::IOExceptionThere is an input/output exception.
Aspose::Words::IncorrectPasswordExceptionThe document is encrypted and requires a password to open, but you supplied an incorrect password.
System::ArgumentExceptionThe name of the file cannot be null or empty string.
Examples

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

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
doc->Save(ArtifactsDir + u"Document.ConvertToPdf.pdf");

◆ Document() [3/6]

Aspose::Words::Document::Document ( const System::String fileName,
const System::SharedPtr< Aspose::Words::Loading::LoadOptions > &  loadOptions 
)

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

Parameters
fileNameFile name of the document to open.
loadOptionsAdditional options to use when loading a document. Can be null.
Exceptions
Aspose::Words::UnsupportedFileFormatExceptionThe document format is not recognized or not supported.
Aspose::Words::FileCorruptedExceptionThe document appears to be corrupted and cannot be loaded.
System::ExceptionThere is a problem with the document and it should be reported to Aspose.Words developers.
System::IO::IOExceptionThere is an input/output exception.
Aspose::Words::IncorrectPasswordExceptionThe document is encrypted and requires a password to open, but you supplied an incorrect password.
System::ArgumentExceptionThe name of the file cannot be null or empty string.
Examples

Shows how to create and load documents.

// There are two ways of creating a Document object using Aspose.Words.
// 1 - Create a blank document:
auto doc = MakeObject<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->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
// 2 - Load a document that exists in the local file system:
doc = MakeObject<Document>(MyDir + u"Document.docx");
// Loaded documents will have contents that we can access and edit.
ASSERT_EQ(u"Hello World!", doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetText().Trim());
// 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 = MakeObject<Document>(MyDir + u"Encrypted.docx", MakeObject<LoadOptions>(u"docPassword"));
ASSERT_EQ(u"Test encrypted document.", doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetText().Trim());

Shows how to load an encrypted Microsoft Word document.

SharedPtr<Document> doc;
// Aspose.Words throw an exception if we try to open an encrypted document without its password.
ASSERT_THROW(doc = MakeObject<Document>(MyDir + u"Encrypted.docx"), IncorrectPasswordException);
// When loading such a document, the password is passed to the document's constructor using a LoadOptions object.
auto options = MakeObject<LoadOptions>(u"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 = MakeObject<Document>(MyDir + u"Encrypted.docx", options);
// 2 - Load the document from a stream:
{
SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(MyDir + u"Encrypted.docx");
doc = MakeObject<Document>(stream, options);
}

◆ Document() [4/6]

Aspose::Words::Document::Document ( const System::SharedPtr< System::IO::Stream > &  stream)

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

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

Parameters
streamStream where to load the document from.
Exceptions
Aspose::Words::UnsupportedFileFormatExceptionThe document format is not recognized or not supported.
Aspose::Words::FileCorruptedExceptionThe document appears to be corrupted and cannot be loaded.
System::ExceptionThere is a problem with the document and it should be reported to Aspose.Words developers.
System::IO::IOExceptionThere is an input/output exception.
Aspose::Words::IncorrectPasswordExceptionThe document is encrypted and requires a password to open, but you supplied an incorrect password.
System::ArgumentNullExceptionThe stream cannot be null.
System::NotSupportedExceptionThe stream does not support reading or seeking.
System::ObjectDisposedExceptionThe stream is a disposed object.
Examples

Shows how to load a document using a stream.

{
SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(MyDir + u"Document.docx");
auto doc = MakeObject<Document>(stream);
ASSERT_EQ(u"Hello World!\r\rHello Word!\r\r\rHello World!", doc->GetText().Trim());
}

Shows how to load a document from a URL.

// Create a URL that points to a Microsoft Word document.
const String url = u"https://omextemplates.content.office.net/support/templates/en-us/tf16402488.dotx";
// Download the document into a byte array, then load that array into a document using a memory stream.
{
auto webClient = MakeObject<System::Net::WebClient>();
ArrayPtr<uint8_t> dataBytes = webClient->DownloadData(url);
{
auto byteStream = MakeObject<System::IO::MemoryStream>(dataBytes);
auto doc = MakeObject<Document>(byteStream);
// At this stage, we can read and edit the document's contents and then save it to the local file system.
ASSERT_EQ(String(u"Use this section to highlight your relevant passions, activities, and how you like to give back. ") +
u"It’s good to include Leadership and volunteer experiences here. " +
u"Or show off important extras like publications, certifications, languages and more.",
doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(4)->GetText().Trim());
doc->Save(ArtifactsDir + u"Document.LoadFromWeb.docx");
}
}

◆ Document() [5/6]

Aspose::Words::Document::Document ( const System::SharedPtr< System::IO::Stream > &  stream,
const System::SharedPtr< Aspose::Words::Loading::LoadOptions > &  loadOptions 
)

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

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

Parameters
streamThe stream where to load the document from.
loadOptionsAdditional options to use when loading a document. Can be null.
Exceptions
Aspose::Words::UnsupportedFileFormatExceptionThe document format is not recognized or not supported.
Aspose::Words::FileCorruptedExceptionThe document appears to be corrupted and cannot be loaded.
System::ExceptionThere is a problem with the document and it should be reported to Aspose.Words developers.
System::IO::IOExceptionThere is an input/output exception.
Aspose::Words::IncorrectPasswordExceptionThe document is encrypted and requires a password to open, but you supplied an incorrect password.
System::ArgumentNullExceptionThe stream cannot be null.
System::NotSupportedExceptionThe stream does not support reading or seeking.
System::ObjectDisposedExceptionThe stream is a disposed object.
Examples

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

{
SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(MyDir + u"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.
auto loadOptions = MakeObject<LoadOptions>();
loadOptions->set_BaseUri(ImageDir);
auto doc = MakeObject<Document>(stream, loadOptions);
// Verify that the first shape of the document contains a valid image.
auto shape = System::DynamicCast<Shape>(doc->GetChild(NodeType::Shape, 0, true));
ASSERT_TRUE(shape->get_IsImage());
ASSERT_FALSE(shape->get_ImageData()->get_ImageBytes() == nullptr);
ASSERT_NEAR(32.0, ConvertUtil::PointToPixel(shape->get_Width()), 0.01);
ASSERT_NEAR(32.0, ConvertUtil::PointToPixel(shape->get_Height()), 0.01);
}

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

const String url = u"https://www.aspose.com/";
{
auto client = MakeObject<System::Net::WebClient>();
{
auto stream = MakeObject<System::IO::MemoryStream>(client->DownloadData(url));
// The URL is used again as a baseUri to ensure that any relative image paths are retrieved correctly.
auto options = MakeObject<LoadOptions>(LoadFormat::Html, u"", url);
// Load the HTML document from stream and pass the LoadOptions object.
auto doc = MakeObject<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 + u"Document.InsertHtmlFromWebPage.docx");
}
}

Shows how to load an encrypted Microsoft Word document.

SharedPtr<Document> doc;
// Aspose.Words throw an exception if we try to open an encrypted document without its password.
ASSERT_THROW(doc = MakeObject<Document>(MyDir + u"Encrypted.docx"), IncorrectPasswordException);
// When loading such a document, the password is passed to the document's constructor using a LoadOptions object.
auto options = MakeObject<LoadOptions>(u"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 = MakeObject<Document>(MyDir + u"Encrypted.docx", options);
// 2 - Load the document from a stream:
{
SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(MyDir + u"Encrypted.docx");
doc = MakeObject<Document>(stream, options);
}

◆ Document() [6/6]

template<typename CharType , typename Traits >
Aspose::Words::Document::Document ( std::basic_istream< CharType, Traits > &  stream,
System::SharedPtr< Aspose::Words::Loading::LoadOptions loadOptions 
)
inline

Member Function Documentation

◆ Accept()

bool Aspose::Words::Document::Accept ( System::SharedPtr< Aspose::Words::DocumentVisitor visitor)
overridevirtual

Accepts a visitor.

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

For more info see the Visitor design pattern.

Parameters
visitorThe visitor that will visit the nodes.
Returns
True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.
Examples

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

void DocStructureToText()
{
auto doc = MakeObject<Document>(MyDir + u"DocumentVisitor-compatible features.docx");
auto visitor = MakeObject<ExDocumentVisitor::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);
std::cout << visitor->GetText() << std::endl;
}
class DocStructurePrinter : public DocumentVisitor
{
public:
DocStructurePrinter() : mDocTraversalDepth(0)
{
mAcceptingNodeChildTree = MakeObject<System::Text::StringBuilder>();
}
String GetText()
{
return mAcceptingNodeChildTree->ToString();
}
VisitorAction VisitDocumentStart(SharedPtr<Document> doc) override
{
int childNodeCount = doc->GetChildNodes(NodeType::Any, true)->get_Count();
IndentAndAppendLine(String(u"[Document start] Child nodes: ") + childNodeCount);
mDocTraversalDepth++;
// Allow the visitor to continue visiting other nodes.
}
VisitorAction VisitDocumentEnd(SharedPtr<Document> doc) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Document end]");
}
VisitorAction VisitSectionStart(SharedPtr<Section> section) override
{
// Get the index of our section within the document.
SharedPtr<NodeCollection> docSections = section->get_Document()->GetChildNodes(NodeType::Section, false);
int sectionIndex = docSections->IndexOf(section);
IndentAndAppendLine(String(u"[Section start] Section index: ") + sectionIndex);
mDocTraversalDepth++;
}
VisitorAction VisitSectionEnd(SharedPtr<Section> section) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Section end]");
}
VisitorAction VisitBodyStart(SharedPtr<Body> body) override
{
int paragraphCount = body->get_Paragraphs()->get_Count();
IndentAndAppendLine(String(u"[Body start] Paragraphs: ") + paragraphCount);
mDocTraversalDepth++;
}
VisitorAction VisitBodyEnd(SharedPtr<Body> body) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Body end]");
}
VisitorAction VisitParagraphStart(SharedPtr<Paragraph> paragraph) override
{
IndentAndAppendLine(u"[Paragraph start]");
mDocTraversalDepth++;
}
VisitorAction VisitParagraphEnd(SharedPtr<Paragraph> paragraph) override
{
mDocTraversalDepth--;
IndentAndAppendLine(u"[Paragraph end]");
}
VisitorAction VisitRun(SharedPtr<Run> run) override
{
IndentAndAppendLine(String(u"[Run] \"") + run->GetText() + u"\"");
}
VisitorAction VisitSubDocument(SharedPtr<SubDocument> subDocument) override
{
IndentAndAppendLine(u"[SubDocument]");
}
private:
int mDocTraversalDepth;
SharedPtr<System::Text::StringBuilder> mAcceptingNodeChildTree;
void IndentAndAppendLine(String text)
{
for (int i = 0; i < mDocTraversalDepth; i++)
{
mAcceptingNodeChildTree->Append(u"| ");
}
mAcceptingNodeChildTree->AppendLine(text);
}
};

Implements Aspose::Words::Node.

◆ AcceptAllRevisions()

void Aspose::Words::Document::AcceptAllRevisions ( )

Accepts all tracked changes in the document.

Examples

Shows how to accept all tracking changes in the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Edit the document while tracking changes to create a few revisions.
doc->StartTrackRevisions(u"John Doe");
builder->Write(u"Hello world! ");
builder->Write(u"Hello again! ");
builder->Write(u"This is another revision.");
doc->StopTrackRevisions();
ASSERT_EQ(3, doc->get_Revisions()->get_Count());
// 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_EQ(0, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"Hello world! Hello again! This is another revision.", doc->GetText().Trim());

◆ AppendDocument() [1/2]

void Aspose::Words::Document::AppendDocument ( const System::SharedPtr< Aspose::Words::Document > &  srcDoc,
Aspose::Words::ImportFormatMode  importFormatMode 
)

Appends the specified document to the end of this document.

Parameters
srcDocThe document to append.
importFormatModeSpecifies how to merge style formatting that clashes.
Examples

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

auto srcDoc = MakeObject<Document>();
srcDoc->get_FirstSection()->get_Body()->AppendParagraph(u"Source document text. ");
auto dstDoc = MakeObject<Document>();
dstDoc->get_FirstSection()->get_Body()->AppendParagraph(u"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 + u"Document.AppendDocument.docx");

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

auto dstDoc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(dstDoc);
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Template Document");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Normal);
builder->Writeln(u"Some content here");
// Append all unencrypted documents with the .doc extension
// from our local file system directory to the base document.
auto isDocFile = [](String item)
{
return item.EndsWith(u".doc");
};
SharedPtr<System::Collections::Generic::List<String>> docFiles = System::IO::Directory::GetFiles(MyDir, u"*.doc")->LINQ_Where(isDocFile)->LINQ_ToList();
for (const auto& fileName : docFiles)
{
SharedPtr<FileFormatInfo> info = FileFormatUtil::DetectFileFormat(fileName);
if (info->get_IsEncrypted())
{
continue;
}
auto srcDoc = MakeObject<Document>(fileName);
dstDoc->AppendDocument(srcDoc, ImportFormatMode::UseDestinationStyles);
}
dstDoc->Save(ArtifactsDir + u"Document.AppendAllDocumentsInFolder.doc");

◆ AppendDocument() [2/2]

void Aspose::Words::Document::AppendDocument ( const System::SharedPtr< Aspose::Words::Document > &  srcDoc,
Aspose::Words::ImportFormatMode  importFormatMode,
const System::SharedPtr< Aspose::Words::ImportFormatOptions > &  importFormatOptions 
)

Appends the specified document to the end of this document.

Parameters
srcDocThe document to append.
importFormatModeSpecifies how to merge style formatting that clashes.
importFormatOptionsAllows to specify options that affect formatting of a result document.
Examples

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

// Load a document with text in a custom style and clone it.
auto srcDoc = MakeObject<Document>(MyDir + u"Custom list numbering.docx");
SharedPtr<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->get_Styles()->idx_get(u"CustomStyle")->get_Font()->set_Color(System::Drawing::Color::get_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.
auto options = MakeObject<ImportFormatOptions>();
options->set_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 + u"DocumentBuilder.AppendDocumentAndResolveStyles.docx");

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

auto dstDoc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(dstDoc);
builder->InsertBreak(BreakType::ParagraphBreak);
dstDoc->get_Lists()->Add(ListTemplate::NumberDefault);
SharedPtr<Aspose::Words::Lists::List> list = dstDoc->get_Lists()->idx_get(0);
builder->get_ListFormat()->set_List(list);
for (int i = 1; i <= 15; i++)
{
builder->Write(String::Format(u"List Item {0}\n", i));
}
auto attachDoc = System::DynamicCast<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.
auto importOptions = MakeObject<ImportFormatOptions>();
importOptions->set_KeepSourceNumbering(keepSourceNumbering);
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->InsertDocument(attachDoc, ImportFormatMode::KeepSourceFormatting, importOptions);
dstDoc->Save(ArtifactsDir + u"DocumentBuilder.InsertDocumentAndResolveStyles.docx");

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

auto srcDoc = MakeObject<Document>(MyDir + u"List item.docx");
auto dstDoc = MakeObject<Document>(MyDir + u"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.
auto builder = MakeObject<DocumentBuilder>(dstDoc);
builder->MoveToDocumentEnd();
builder->InsertBreak(BreakType::SectionBreakNewPage);
auto options = MakeObject<ImportFormatOptions>();
options->set_KeepSourceNumbering(keepSourceNumbering);
builder->InsertDocument(srcDoc, ImportFormatMode::KeepSourceFormatting, options);
dstDoc->UpdateListLabels();

◆ Cleanup() [1/2]

void Aspose::Words::Document::Cleanup ( )

Cleans unused styles and lists from the document.

Examples

Shows how to remove unused custom styles from a document.

auto doc = MakeObject<Document>();
doc->get_Styles()->Add(StyleType::List, u"MyListStyle1");
doc->get_Styles()->Add(StyleType::List, u"MyListStyle2");
doc->get_Styles()->Add(StyleType::Character, u"MyParagraphStyle1");
doc->get_Styles()->Add(StyleType::Character, u"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_EQ(8, doc->get_Styles()->get_Count());
// Apply a custom character style, and then a custom list style. Doing so will mark the styles as "used".
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Style(doc->get_Styles()->idx_get(u"MyParagraphStyle1"));
builder->Writeln(u"Hello world!");
SharedPtr<Aspose::Words::Lists::List> list = doc->get_Lists()->Add(doc->get_Styles()->idx_get(u"MyListStyle1"));
builder->get_ListFormat()->set_List(list);
builder->Writeln(u"Item 1");
builder->Writeln(u"Item 2");
doc->Cleanup();
ASSERT_EQ(6, doc->get_Styles()->get_Count());
// Removing every node that a custom style is applied to marks it as "unused" again.
// Run the Cleanup method again to remove them.
doc->get_FirstSection()->get_Body()->RemoveAllChildren();
doc->Cleanup();
ASSERT_EQ(4, doc->get_Styles()->get_Count());

◆ Cleanup() [2/2]

void Aspose::Words::Document::Cleanup ( const System::SharedPtr< Aspose::Words::CleanupOptions > &  options)

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

Examples

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

auto doc = MakeObject<Document>();
doc->get_Styles()->Add(StyleType::List, u"MyListStyle1");
doc->get_Styles()->Add(StyleType::List, u"MyListStyle2");
doc->get_Styles()->Add(StyleType::Character, u"MyParagraphStyle1");
doc->get_Styles()->Add(StyleType::Character, u"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_EQ(8, doc->get_Styles()->get_Count());
// Apply a custom character style, and then a custom list style. Doing so will mark them as "used".
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Style(doc->get_Styles()->idx_get(u"MyParagraphStyle1"));
builder->Writeln(u"Hello world!");
SharedPtr<Aspose::Words::Lists::List> list = doc->get_Lists()->Add(doc->get_Styles()->idx_get(u"MyListStyle1"));
builder->get_ListFormat()->set_List(list);
builder->Writeln(u"Item 1");
builder->Writeln(u"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.
auto cleanupOptions = MakeObject<CleanupOptions>();
cleanupOptions->set_UnusedLists(true);
cleanupOptions->set_UnusedStyles(true);
cleanupOptions->set_UnusedBuiltinStyles(true);
doc->Cleanup(cleanupOptions);
ASSERT_EQ(4, doc->get_Styles()->get_Count());
// Removing every node that a custom style is applied to marks it as "unused" again.
// Rerun the Cleanup method to remove them.
doc->get_FirstSection()->get_Body()->RemoveAllChildren();
doc->Cleanup(cleanupOptions);
ASSERT_EQ(2, doc->get_Styles()->get_Count());

◆ Clone()

System::SharedPtr<Aspose::Words::Document> Aspose::Words::Document::Clone ( )

Performs a deep copy of the Document.

Returns
The cloned document.
Examples

Shows how to deep clone a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"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.
SharedPtr<Document> clone = doc->Clone();
ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)->GetText(),
clone->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)->get_Text());
ASSERT_NE(System::ObjectExt::GetHashCode(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)),
System::ObjectExt::GetHashCode(clone->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)));

◆ Compare() [1/2]

void Aspose::Words::Document::Compare ( const System::SharedPtr< Aspose::Words::Document > &  document,
const System::String author,
System::DateTime  dateTime 
)

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

The following document nodes are not compared at the moment:

Note
Documents must not have revisions before comparison.
Parameters
documentDocument to compare.
authorInitials of the author to use for revisions.
dateTimeThe date and time to use for revisions.
Examples

Shows how to compare documents.

auto docOriginal = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(docOriginal);
builder->Writeln(u"This is the original document.");
auto docEdited = MakeObject<Document>();
builder = MakeObject<DocumentBuilder>(docEdited);
builder->Writeln(u"This is the edited document.");
// Comparing documents with revisions will throw an exception.
if (docOriginal->get_Revisions()->get_Count() == 0 && docEdited->get_Revisions()->get_Count() == 0)
{
docOriginal->Compare(docEdited, u"authorName", System::DateTime::get_Now());
}
// After the comparison, the original document will gain a new revision
// for every element that is different in the edited document.
for (const auto& r : System::IterateOver(docOriginal->get_Revisions()))
{
std::cout << String::Format(u"Revision type: {0}, on a node of type \"{1}\"", r->get_RevisionType(), r->get_ParentNode()->get_NodeType())
<< std::endl;
std::cout << "\tChanged text: \"" << r->get_ParentNode()->GetText() << "\"" << std::endl;
}
// Accepting these revisions will transform the original document into the edited document.
docOriginal->get_Revisions()->AcceptAll();
ASSERT_EQ(docOriginal->GetText(), docEdited->GetText());

◆ Compare() [2/2]

void Aspose::Words::Document::Compare ( const System::SharedPtr< Aspose::Words::Document > &  document,
const System::String author,
System::DateTime  dateTime,
const System::SharedPtr< Aspose::Words::Comparing::CompareOptions > &  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.

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.
auto docOriginal = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(docOriginal);
// Paragraph text referenced with an endnote:
builder->Writeln(u"Hello world! This is the first paragraph.");
builder->InsertFootnote(FootnoteType::Endnote, u"Original endnote text.");
// Table:
builder->StartTable();
builder->InsertCell();
builder->Write(u"Original cell 1 text");
builder->InsertCell();
builder->Write(u"Original cell 2 text");
builder->EndTable();
// Textbox:
SharedPtr<Shape> textBox = builder->InsertShape(ShapeType::TextBox, 150, 20);
builder->MoveTo(textBox->get_FirstParagraph());
builder->Write(u"Original textbox contents");
// DATE field:
builder->MoveTo(docOriginal->get_FirstSection()->get_Body()->AppendParagraph(u""));
builder->InsertField(u" DATE ");
// Comment:
auto newComment = MakeObject<Comment>(docOriginal, u"John Doe", u"J.D.", System::DateTime::get_Now());
newComment->SetText(u"Original comment.");
builder->get_CurrentParagraph()->AppendChild(newComment);
// Header:
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Writeln(u"Original header contents.");
// Create a clone of our document and perform a quick edit on each of the cloned document's elements.
auto docEdited = System::DynamicCast<Document>(docOriginal->Clone(true));
SharedPtr<Paragraph> firstParagraph = docEdited->get_FirstSection()->get_Body()->get_FirstParagraph();
firstParagraph->get_Runs()->idx_get(0)->set_Text(u"hello world! this is the first paragraph, after editing.");
firstParagraph->get_ParagraphFormat()->set_Style(docEdited->get_Styles()->idx_get(StyleIdentifier::Heading1));
(System::DynamicCast<Footnote>(docEdited->GetChild(NodeType::Footnote, 0, true)))
->get_FirstParagraph()
->get_Runs()
->idx_get(1)
->set_Text(u"Edited endnote text.");
(System::DynamicCast<Table>(docEdited->GetChild(NodeType::Table, 0, true)))
->get_FirstRow()
->get_Cells()
->idx_get(1)
->get_FirstParagraph()
->get_Runs()
->idx_get(0)
->set_Text(u"Edited Cell 2 contents");
(System::DynamicCast<Shape>(docEdited->GetChild(NodeType::Shape, 0, true)))
->get_FirstParagraph()
->get_Runs()
->idx_get(0)
->set_Text(u"Edited textbox contents");
(System::DynamicCast<FieldDate>(docEdited->get_Range()->get_Fields()->idx_get(0)))->set_UseLunarCalendar(true);
(System::DynamicCast<Comment>(docEdited->GetChild(NodeType::Comment, 0, true)))
->get_FirstParagraph()
->get_Runs()
->idx_get(0)
->set_Text(u"Edited comment.");
docEdited->get_FirstSection()
->get_HeadersFooters()
->get_FirstParagraph()
->get_Runs()
->idx_get(0)
->set_Text(u"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.
auto compareOptions = MakeObject<Aspose::Words::Comparing::CompareOptions>();
compareOptions->set_IgnoreFormatting(false);
compareOptions->set_IgnoreCaseChanges(false);
compareOptions->set_IgnoreComments(false);
compareOptions->set_IgnoreTables(false);
compareOptions->set_IgnoreFields(false);
compareOptions->set_IgnoreFootnotes(false);
compareOptions->set_IgnoreTextboxes(false);
compareOptions->set_IgnoreHeadersAndFooters(false);
compareOptions->set_Target(ComparisonTargetType::New);
docOriginal->Compare(docEdited, u"John Doe", System::DateTime::get_Now(), compareOptions);
docOriginal->Save(ArtifactsDir + u"Document.CompareOptions.docx");

◆ CopyStylesFromTemplate() [1/2]

void Aspose::Words::Document::CopyStylesFromTemplate ( const System::SharedPtr< Aspose::Words::Document > &  template_)

Copies styles from the specified template to a document.

Examples

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

auto template_ = MakeObject<Document>(MyDir + u"Rendering.docx");
auto target = MakeObject<Document>(MyDir + u"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.
auto template_ = MakeObject<Document>();
SharedPtr<Style> style = template_->get_Styles()->Add(StyleType::Paragraph, u"TemplateStyle1");
style->get_Font()->set_Name(u"Times New Roman");
style->get_Font()->set_Color(System::Drawing::Color::get_Navy());
style = template_->get_Styles()->Add(StyleType::Paragraph, u"TemplateStyle2");
style->get_Font()->set_Name(u"Arial");
style->get_Font()->set_Color(System::Drawing::Color::get_DeepSkyBlue());
style = template_->get_Styles()->Add(StyleType::Paragraph, u"TemplateStyle3");
style->get_Font()->set_Name(u"Courier New");
style->get_Font()->set_Color(System::Drawing::Color::get_RoyalBlue());
ASSERT_EQ(7, template_->get_Styles()->get_Count());
// Create a document which we will copy the styles to.
auto target = MakeObject<Document>();
// Create a style with the same name as a style from the template document and add it to the target document.
style = target->get_Styles()->Add(StyleType::Paragraph, u"TemplateStyle3");
style->get_Font()->set_Name(u"Calibri");
style->get_Font()->set_Color(System::Drawing::Color::get_Orange());
ASSERT_EQ(5, target->get_Styles()->get_Count());
// 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_EQ(7, target->get_Styles()->get_Count());
ASSERT_EQ(u"Courier New", target->get_Styles()->idx_get(u"TemplateStyle3")->get_Font()->get_Name());
ASSERT_EQ(System::Drawing::Color::get_RoyalBlue().ToArgb(), target->get_Styles()->idx_get(u"TemplateStyle3")->get_Font()->get_Color().ToArgb());
// 2 - Passing the local system filename of a template document:
target->CopyStylesFromTemplate(MyDir + u"Rendering.docx");
ASSERT_EQ(21, target->get_Styles()->get_Count());

◆ CopyStylesFromTemplate() [2/2]

void Aspose::Words::Document::CopyStylesFromTemplate ( const System::String template_)

Copies styles from the specified template to a document.

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.
auto template_ = MakeObject<Document>();
SharedPtr<Style> style = template_->get_Styles()->Add(StyleType::Paragraph, u"TemplateStyle1");
style->get_Font()->set_Name(u"Times New Roman");
style->get_Font()->set_Color(System::Drawing::Color::get_Navy());
style = template_->get_Styles()->Add(StyleType::Paragraph, u"TemplateStyle2");
style->get_Font()->set_Name(u"Arial");
style->get_Font()->set_Color(System::Drawing::Color::get_DeepSkyBlue());
style = template_->get_Styles()->Add(StyleType::Paragraph, u"TemplateStyle3");
style->get_Font()->set_Name(u"Courier New");
style->get_Font()->set_Color(System::Drawing::Color::get_RoyalBlue());
ASSERT_EQ(7, template_->get_Styles()->get_Count());
// Create a document which we will copy the styles to.
auto target = MakeObject<Document>();
// Create a style with the same name as a style from the template document and add it to the target document.
style = target->get_Styles()->Add(StyleType::Paragraph, u"TemplateStyle3");
style->get_Font()->set_Name(u"Calibri");
style->get_Font()->set_Color(System::Drawing::Color::get_Orange());
ASSERT_EQ(5, target->get_Styles()->get_Count());
// 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_EQ(7, target->get_Styles()->get_Count());
ASSERT_EQ(u"Courier New", target->get_Styles()->idx_get(u"TemplateStyle3")->get_Font()->get_Name());
ASSERT_EQ(System::Drawing::Color::get_RoyalBlue().ToArgb(), target->get_Styles()->idx_get(u"TemplateStyle3")->get_Font()->get_Color().ToArgb());
// 2 - Passing the local system filename of a template document:
target->CopyStylesFromTemplate(MyDir + u"Rendering.docx");
ASSERT_EQ(21, target->get_Styles()->get_Count());

◆ EnsureMinimum()

void Aspose::Words::Document::EnsureMinimum ( )

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

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.
auto doc = MakeObject<Document>();
SharedPtr<NodeCollection> nodes = doc->GetChildNodes(NodeType::Any, true);
ASSERT_EQ(NodeType::Section, nodes->idx_get(0)->get_NodeType());
ASPOSE_ASSERT_EQ(doc, nodes->idx_get(0)->get_ParentNode());
ASSERT_EQ(NodeType::Body, nodes->idx_get(1)->get_NodeType());
ASPOSE_ASSERT_EQ(nodes->idx_get(0), nodes->idx_get(1)->get_ParentNode());
ASSERT_EQ(NodeType::Paragraph, nodes->idx_get(2)->get_NodeType());
ASPOSE_ASSERT_EQ(nodes->idx_get(1), nodes->idx_get(2)->get_ParentNode());
// 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_EQ(0, doc->GetChildNodes(NodeType::Any, true)->get_Count());
// Call this method to make sure that the document has at least those three nodes so we can edit it again.
doc->EnsureMinimum();
ASSERT_EQ(NodeType::Section, nodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Body, nodes->idx_get(1)->get_NodeType());
ASSERT_EQ(NodeType::Paragraph, nodes->idx_get(2)->get_NodeType());
(System::DynamicCast<Paragraph>(nodes->idx_get(2)))->get_Runs()->Add(MakeObject<Run>(doc, u"Hello world!"));

◆ ExpandTableStylesToDirectFormatting()

void Aspose::Words::Document::ExpandTableStylesToDirectFormatting ( )

Converts formatting specified in table styles into direct formatting on tables in the document.

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

Shows how to apply the properties of a table's style directly to the table's elements.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Hello world!");
builder->EndTable();
auto tableStyle = System::DynamicCast<TableStyle>(doc->get_Styles()->Add(StyleType::Table, u"MyTableStyle1"));
tableStyle->set_RowStripe(3);
tableStyle->set_CellSpacing(5);
tableStyle->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_AntiqueWhite());
tableStyle->get_Borders()->set_Color(System::Drawing::Color::get_Blue());
tableStyle->get_Borders()->set_LineStyle(LineStyle::DotDash);
table->set_Style(tableStyle);
// This method concerns table style properties such as the ones we set above.
doc->ExpandTableStylesToDirectFormatting();
doc->Save(ArtifactsDir + u"Document.TableStyleToDirectFormatting.docx");

◆ ExtractPages()

System::SharedPtr<Aspose::Words::Document> Aspose::Words::Document::ExtractPages ( int32_t  index,
int32_t  count 
)

Returns the Document object representing specified range of pages.

Parameters
indexThe zero-based index of the first page to extract.
countNumber of pages to be extracted.
Examples

Shows how to get specified range of pages from the document.

auto doc = MakeObject<Document>(MyDir + u"Layout entities.docx");
doc = doc->ExtractPages(0, 2);
doc->Save(ArtifactsDir + u"Document.ExtractPages.docx");

◆ get_AttachedTemplate()

System::String Aspose::Words::Document::get_AttachedTemplate ( )

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

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

Exceptions
System::ArgumentNullExceptionThrows if you attempt to set to a null value.
See also
Aspose::Words::Properties::BuiltInDocumentProperties::get_Template
Examples

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

auto doc = MakeObject<Document>();
// Enable automatic style updating, but do not attach a template document.
doc->set_AutomaticallyUpdateStyles(true);
ASSERT_EQ(String::Empty, doc->get_AttachedTemplate());
// 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.
SharedPtr<SaveOptions> options = SaveOptions::CreateSaveOptions(u"Document.DefaultTemplate.docx");
options->set_DefaultTemplate(MyDir + u"Business brochure.dotx");
doc->Save(ArtifactsDir + u"Document.DefaultTemplate.docx", options);

◆ get_AutomaticallyUpdateStyles()

bool Aspose::Words::Document::get_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.

Examples

Shows how to attach a template to a document.

auto doc = MakeObject<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_EQ(String::Empty, doc->get_AttachedTemplate());
// Attach a template, then set the flag to apply style changes
// within the template to styles in our document.
doc->set_AttachedTemplate(MyDir + u"Business brochure.dotx");
doc->set_AutomaticallyUpdateStyles(true);
doc->Save(ArtifactsDir + u"Document.AutomaticallyUpdateStyles.docx");

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

auto doc = MakeObject<Document>();
// Enable automatic style updating, but do not attach a template document.
doc->set_AutomaticallyUpdateStyles(true);
ASSERT_EQ(String::Empty, doc->get_AttachedTemplate());
// 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.
SharedPtr<SaveOptions> options = SaveOptions::CreateSaveOptions(u"Document.DefaultTemplate.docx");
options->set_DefaultTemplate(MyDir + u"Business brochure.dotx");
doc->Save(ArtifactsDir + u"Document.DefaultTemplate.docx", options);

◆ get_BuiltInDocumentProperties()

System::SharedPtr<Aspose::Words::Properties::BuiltInDocumentProperties> Aspose::Words::Document::get_BuiltInDocumentProperties ( ) const

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

Examples

Shows how to work with built-in document properties.

auto doc = MakeObject<Document>(MyDir + u"Properties.docx");
// The "Document" object contains some of its metadata in its members.
std::cout << "Document filename:\n\t \"" << doc->get_OriginalFileName() << "\"" << std::endl;
// The document also stores metadata in its built-in properties.
// Each built-in property is a member of the document's "BuiltInDocumentProperties" object.
std::cout << "Built-in Properties:" << std::endl;
for (const auto& docProperty : System::IterateOver(doc->get_BuiltInDocumentProperties()))
{
std::cout << docProperty->get_Name() << std::endl;
std::cout << String::Format(u"\tType:\t{0}", docProperty->get_Type()) << std::endl;
// Some properties may store multiple values.
if (System::ObjectExt::Is<System::Collections::Generic::ICollection<SharedPtr<System::Object>>>(docProperty->get_Value()))
{
for (const auto& value : System::IterateOver(
System::DynamicCast_noexcept<System::Collections::Generic::ICollection<SharedPtr<System::Object>>>(docProperty->get_Value())))
{
std::cout << "\tValue:\t\"" << value << "\"" << std::endl;
}
}
else
{
std::cout << "\tValue:\t\"" << docProperty->get_Value() << "\"" << std::endl;
}
}

◆ get_CompatibilityOptions()

System::SharedPtr<Aspose::Words::Settings::CompatibilityOptions> Aspose::Words::Document::get_CompatibilityOptions ( )

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

◆ get_Compliance()

Aspose::Words::Saving::OoxmlCompliance Aspose::Words::Document::get_Compliance ( )

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

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

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.
auto doc = MakeObject<Document>(MyDir + u"Document.doc");
ASSERT_EQ(doc->get_Compliance(), OoxmlCompliance::Ecma376_2006);
doc = MakeObject<Document>(MyDir + u"Document.docx");
ASSERT_EQ(doc->get_Compliance(), OoxmlCompliance::Iso29500_2008_Transitional);

◆ get_CustomDocumentProperties()

System::SharedPtr<Aspose::Words::Properties::CustomDocumentProperties> Aspose::Words::Document::get_CustomDocumentProperties ( )

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

Examples

Shows how to work with built-in document properties.

auto doc = MakeObject<Document>(MyDir + u"Properties.docx");
// The "Document" object contains some of its metadata in its members.
std::cout << "Document filename:\n\t \"" << doc->get_OriginalFileName() << "\"" << std::endl;
// The document also stores metadata in its built-in properties.
// Each built-in property is a member of the document's "BuiltInDocumentProperties" object.
std::cout << "Built-in Properties:" << std::endl;
for (const auto& docProperty : System::IterateOver(doc->get_BuiltInDocumentProperties()))
{
std::cout << docProperty->get_Name() << std::endl;
std::cout << String::Format(u"\tType:\t{0}", docProperty->get_Type()) << std::endl;
// Some properties may store multiple values.
if (System::ObjectExt::Is<System::Collections::Generic::ICollection<SharedPtr<System::Object>>>(docProperty->get_Value()))
{
for (const auto& value : System::IterateOver(
System::DynamicCast_noexcept<System::Collections::Generic::ICollection<SharedPtr<System::Object>>>(docProperty->get_Value())))
{
std::cout << "\tValue:\t\"" << value << "\"" << std::endl;
}
}
else
{
std::cout << "\tValue:\t\"" << docProperty->get_Value() << "\"" << std::endl;
}
}

◆ get_CustomXmlParts()

System::SharedPtr<Aspose::Words::Markup::CustomXmlPartCollection> Aspose::Words::Document::get_CustomXmlParts ( ) const

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

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

This property cannot be null.

See also
Aspose::Words::Markup::CustomXmlPart
Examples

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

auto doc = MakeObject<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 = System::Guid::NewGuid().ToString(u"B");
String xmlPartContent = u"<root><text>Hello world!</text></root>";
SharedPtr<CustomXmlPart> xmlPart = doc->get_CustomXmlParts()->Add(xmlPartId, xmlPartContent);
ASPOSE_ASSERT_EQ(System::Text::Encoding::get_ASCII()->GetBytes(xmlPartContent), xmlPart->get_Data());
ASSERT_EQ(xmlPartId, xmlPart->get_Id());
// Below are two ways to refer to XML parts.
// 1 - By an index in the custom XML part collection:
ASPOSE_ASSERT_EQ(xmlPart, doc->get_CustomXmlParts()->idx_get(0));
// 2 - By GUID:
ASPOSE_ASSERT_EQ(xmlPart, doc->get_CustomXmlParts()->GetById(xmlPartId));
// Add an XML schema association.
xmlPart->get_Schemas()->Add(u"http://www.w3.org/2001/XMLSchema");
// Clone a part, and then insert it into the collection.
SharedPtr<CustomXmlPart> xmlPartClone = xmlPart->Clone();
xmlPartClone->set_Id(System::Guid::NewGuid().ToString(u"B"));
doc->get_CustomXmlParts()->Add(xmlPartClone);
ASSERT_EQ(2, doc->get_CustomXmlParts()->get_Count());
// Iterate through the collection and print the contents of each part.
{
SharedPtr<System::Collections::Generic::IEnumerator<SharedPtr<CustomXmlPart>>> enumerator = doc->get_CustomXmlParts()->GetEnumerator();
int index = 0;
while (enumerator->MoveNext())
{
std::cout << "XML part index " << index << ", ID: " << enumerator->get_Current()->get_Id() << std::endl;
std::cout << "\tContent: " << System::Text::Encoding::get_UTF8()->GetString(enumerator->get_Current()->get_Data()) << std::endl;
index++;
}
}
// Use the "RemoveAt" method to remove the cloned part by index.
doc->get_CustomXmlParts()->RemoveAt(1);
ASSERT_EQ(1, doc->get_CustomXmlParts()->get_Count());
// Clone the XML parts collection, and then use the "Clear" method to remove all its elements at once.
SharedPtr<CustomXmlPartCollection> customXmlParts = doc->get_CustomXmlParts()->Clone();
customXmlParts->Clear();
// Create a structured document tag that will display our part's contents and insert it into the document body.
auto tag = MakeObject<StructuredDocumentTag>(doc, SdtType::PlainText, MarkupLevel::Block);
tag->get_XmlMapping()->SetMapping(xmlPart, u"/root[1]/text[1]", String::Empty);
doc->get_FirstSection()->get_Body()->AppendChild(tag);
doc->Save(ArtifactsDir + u"StructuredDocumentTag.CustomXml.docx");

◆ get_DefaultTabStop()

double Aspose::Words::Document::get_DefaultTabStop ( )

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

See also
Aspose::Words::TabStopCollection
Aspose::Words::TabStop
Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Set tab stops to appear every 72 points (1 inch).
builder->get_Document()->set_DefaultTabStop(72);
// Each tab character snaps the text after it to the next closest tab stop position.
builder->Writeln(String(u"Hello") + ControlChar::Tab() + u"World!");
builder->Writeln(String(u"Hello") + ControlChar::TabChar + u"World!");

◆ get_DigitalSignatures()

System::SharedPtr<Aspose::Words::DigitalSignatures::DigitalSignatureCollection> Aspose::Words::Document::get_DigitalSignatures ( ) const

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

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

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

Examples

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

auto doc = MakeObject<Document>(MyDir + u"Digitally signed.docx");
for (const auto& signature : doc->get_DigitalSignatures())
{
std::cout << (signature->get_IsValid() ? String(u"Valid") : String(u"Invalid")) << " signature: " << std::endl;
std::cout << "\tReason:\t" << signature->get_Comments() << std::endl;
std::cout << String::Format(u"\tType:\t{0}", signature->get_SignatureType()) << std::endl;
std::cout << "\tSign time:\t" << signature->get_SignTime() << std::endl;
std::cout << "\tSubject name:\t" << signature->get_CertificateHolder()->get_Certificate()->get_SubjectName() << std::endl;
std::cout << "\tIssuer name:\t" << signature->get_CertificateHolder()->get_Certificate()->get_IssuerName()->get_Name() << std::endl;
std::cout << std::endl;
}

Shows how to sign documents with X.509 certificates.

// Verify that a document is not signed.
ASSERT_FALSE(FileFormatUtil::DetectFileFormat(MyDir + u"Document.docx")->get_HasDigitalSignature());
// Create a CertificateHolder object from a PKCS12 file, which we will use to sign the document.
SharedPtr<CertificateHolder> certificateHolder = CertificateHolder::Create(MyDir + u"morzal.pfx", u"aw", nullptr);
// 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.
auto signOptions = MakeObject<SignOptions>();
signOptions->set_SignTime(System::DateTime::get_Now());
DigitalSignatureUtil::Sign(MyDir + u"Document.docx", ArtifactsDir + u"Document.DigitalSignature.docx", certificateHolder, signOptions);
ASSERT_TRUE(FileFormatUtil::DetectFileFormat(ArtifactsDir + u"Document.DigitalSignature.docx")->get_HasDigitalSignature());
// 2 - Take a document from a stream and save a signed copy to another stream.
{
auto inDoc = MakeObject<System::IO::FileStream>(MyDir + u"Document.docx", System::IO::FileMode::Open);
{
auto outDoc = MakeObject<System::IO::FileStream>(ArtifactsDir + u"Document.DigitalSignature.docx", System::IO::FileMode::Create);
DigitalSignatureUtil::Sign(inDoc, outDoc, certificateHolder);
}
}
ASSERT_TRUE(FileFormatUtil::DetectFileFormat(ArtifactsDir + u"Document.DigitalSignature.docx")->get_HasDigitalSignature());
// Please verify that all of the document's digital signatures are valid and check their details.
auto signedDoc = MakeObject<Document>(ArtifactsDir + u"Document.DigitalSignature.docx");
SharedPtr<DigitalSignatureCollection> digitalSignatureCollection = signedDoc->get_DigitalSignatures();
ASSERT_TRUE(digitalSignatureCollection->get_IsValid());
ASSERT_EQ(1, digitalSignatureCollection->get_Count());
ASSERT_EQ(DigitalSignatureType::XmlDsig, digitalSignatureCollection->idx_get(0)->get_SignatureType());
ASSERT_EQ(u"CN=Morzal.Me", signedDoc->get_DigitalSignatures()->idx_get(0)->get_IssuerName());
ASSERT_EQ(u"CN=Morzal.Me", signedDoc->get_DigitalSignatures()->idx_get(0)->get_SubjectName());

◆ get_EndnoteOptions()

System::SharedPtr<Aspose::Words::Notes::EndnoteOptions> Aspose::Words::Document::get_EndnoteOptions ( )

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

Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Hello world!");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote contents.");
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->Write(u"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->get_EndnoteOptions()->set_Position(endnotePosition);
doc->Save(ArtifactsDir + u"InlineStory.PositionEndnote.docx");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 2.");
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 3.", u"Custom footnote reference mark");
builder->InsertParagraph();
builder->Write(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 2.");
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 3.", u"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_EQ(NumberStyle::Arabic, doc->get_FootnoteOptions()->get_NumberStyle());
ASSERT_EQ(NumberStyle::LowercaseRoman, doc->get_EndnoteOptions()->get_NumberStyle());
// 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->get_FootnoteOptions()->set_NumberStyle(NumberStyle::UppercaseRoman);
doc->get_EndnoteOptions()->set_NumberStyle(NumberStyle::UppercaseLetter);
doc->Save(ArtifactsDir + u"InlineStory.RefMarkNumberStyle.docx");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 2.");
builder->InsertBreak(BreakType::PageBreak);
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 3.");
builder->Write(u"Text 4. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 4.");
builder->InsertBreak(BreakType::PageBreak);
builder->Write(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 2.");
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 3.");
builder->Write(u"Text 4. ");
builder->InsertFootnote(FootnoteType::Endnote, u"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_EQ(doc->get_FootnoteOptions()->get_RestartRule(), FootnoteNumberingRule::Default);
ASSERT_EQ(FootnoteNumberingRule::Default, FootnoteNumberingRule::Continuous);
// We can use the "RestartRule" property to get the document to restart
// the footnote/endnote counts at a new page or section.
doc->get_FootnoteOptions()->set_RestartRule(FootnoteNumberingRule::RestartPage);
doc->get_EndnoteOptions()->set_RestartRule(FootnoteNumberingRule::RestartSection);
doc->Save(ArtifactsDir + u"InlineStory.NumberingRule.docx");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 2.");
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 3.");
builder->InsertParagraph();
builder->Write(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 2.");
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Endnote, u"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_EQ(1, doc->get_FootnoteOptions()->get_StartNumber());
ASSERT_EQ(1, doc->get_EndnoteOptions()->get_StartNumber());
// We can use the "StartNumber" property to get the document to
// begin a footnote or endnote count at a different number.
doc->get_EndnoteOptions()->set_NumberStyle(NumberStyle::Arabic);
doc->get_EndnoteOptions()->set_StartNumber(50);
doc->Save(ArtifactsDir + u"InlineStory.StartNumber.docx");

◆ get_FieldOptions()

System::SharedPtr<Aspose::Words::Fields::FieldOptions> Aspose::Words::Document::get_FieldOptions ( )

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

◆ get_FirstSection()

System::SharedPtr<Aspose::Words::Section> Aspose::Words::Document::get_FirstSection ( )

Gets the first section in the document.

Examples

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

auto doc = MakeObject<Document>(MyDir + u"Footer.docx");
SharedPtr<HeaderFooterCollection> headersFooters = doc->get_FirstSection()->get_HeadersFooters();
SharedPtr<HeaderFooter> footer = headersFooters->idx_get(HeaderFooterType::FooterPrimary);
auto options = MakeObject<FindReplaceOptions>();
options->set_MatchCase(false);
options->set_FindWholeWordsOnly(false);
int currentYear = System::DateTime::get_Now().get_Year();
footer->get_Range()->Replace(u"(C) 2006 Aspose Pty Ltd.", String::Format(u"Copyright (C) {0} by Aspose Pty Ltd.", currentYear), options);
doc->Save(ArtifactsDir + u"HeaderFooter.ReplaceText.docx");

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

auto doc = MakeObject<Document>();
// A blank document contains one section by default,
// which contains child nodes that we can edit.
ASSERT_EQ(1, doc->get_Sections()->get_Count());
// Use a document builder to add text to the first section.
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world!");
// Create a second section by inserting a section break.
builder->InsertBreak(BreakType::SectionBreakNewPage);
ASSERT_EQ(2, doc->get_Sections()->get_Count());
// 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->get_LastSection()->get_PageSetup()->get_TextColumns()->SetCount(2);
builder->Writeln(u"Column 1.");
builder->InsertBreak(BreakType::ColumnBreak);
builder->Writeln(u"Column 2.");
ASSERT_EQ(1, doc->get_FirstSection()->get_PageSetup()->get_TextColumns()->get_Count());
ASSERT_EQ(2, doc->get_LastSection()->get_PageSetup()->get_TextColumns()->get_Count());
doc->Save(ArtifactsDir + u"Section.Create.docx");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"Section 1");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Primary header");
builder->MoveToHeaderFooter(HeaderFooterType::FooterPrimary);
builder->Write(u"Primary footer");
SharedPtr<Section> section = doc->get_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.
for (const auto& node : System::IterateOver(section))
{
switch (node->get_NodeType())
{
auto body = System::DynamicCast<Body>(node);
std::cout << "Body:" << std::endl;
std::cout << "\t\"" << body->GetText().Trim() << "\"" << std::endl;
break;
}
auto headerFooter = System::DynamicCast<HeaderFooter>(node);
std::cout << String::Format(u"HeaderFooter type: {0}:", headerFooter->get_HeaderFooterType()) << std::endl;
std::cout << "\t\"" << headerFooter->GetText().Trim() << "\"" << std::endl;
break;
}
default: {
throw System::Exception(u"Unexpected node type in a section.");
}
}
}

◆ get_FontSettings()

System::SharedPtr<Aspose::Words::Fonts::FontSettings> Aspose::Words::Document::get_FontSettings ( ) const

Gets or sets document font settings.

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

The default value is null.

Examples

Shows how set font substitution rules.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Name(u"Arial");
builder->Writeln(u"Hello world!");
builder->get_Font()->set_Name(u"Amethysta");
builder->Writeln(u"The quick brown fox jumps over the lazy dog.");
ArrayPtr<SharedPtr<FontSourceBase>> fontSources = FontSettings::get_DefaultInstance()->GetFontsSources();
// The default font sources contain the first font that the document uses.
ASSERT_EQ(1, fontSources->get_Length());
ASSERT_TRUE(fontSources[0]->GetAvailableFonts()->LINQ_Any([](SharedPtr<PhysicalFontInfo> f) { return f->get_FullFontName() == u"Arial"; }));
// The second font, "Amethysta", is unavailable.
ASSERT_FALSE(fontSources[0]->GetAvailableFonts()->LINQ_Any([](SharedPtr<PhysicalFontInfo> f) { return f->get_FullFontName() == u"Amethysta"; }));
// 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->set_FontSettings(MakeObject<FontSettings>());
doc->get_FontSettings()->get_SubstitutionSettings()->get_TableSubstitution()->SetSubstitutes(u"Amethysta",
MakeArray<String>({u"Arvo", u"Courier New"}));
// "Amethysta" is unavailable, and the substitution rule states that the first font to use as a substitute is "Arvo".
ASSERT_FALSE(fontSources[0]->GetAvailableFonts()->LINQ_Any([](SharedPtr<PhysicalFontInfo> f) { return f->get_FullFontName() == u"Arvo"; }));
// "Arvo" is also unavailable, but "Courier New" is.
ASSERT_TRUE(fontSources[0]->GetAvailableFonts()->LINQ_Any([](SharedPtr<PhysicalFontInfo> f) { return f->get_FullFontName() == u"Courier New"; }));
// The output document will display the text that uses the "Amethysta" font formatted with "Courier New".
doc->Save(ArtifactsDir + u"FontSettings.TableSubstitution.pdf");

◆ get_FootnoteOptions()

System::SharedPtr<Aspose::Words::Notes::FootnoteOptions> Aspose::Words::Document::get_FootnoteOptions ( )

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

Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Hello world!");
builder->InsertFootnote(FootnoteType::Footnote, u"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->get_FootnoteOptions()->set_Position(footnotePosition);
doc->Save(ArtifactsDir + u"InlineStory.PositionFootnote.docx");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 2.");
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 3.", u"Custom footnote reference mark");
builder->InsertParagraph();
builder->Write(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 2.");
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 3.", u"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_EQ(NumberStyle::Arabic, doc->get_FootnoteOptions()->get_NumberStyle());
ASSERT_EQ(NumberStyle::LowercaseRoman, doc->get_EndnoteOptions()->get_NumberStyle());
// 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->get_FootnoteOptions()->set_NumberStyle(NumberStyle::UppercaseRoman);
doc->get_EndnoteOptions()->set_NumberStyle(NumberStyle::UppercaseLetter);
doc->Save(ArtifactsDir + u"InlineStory.RefMarkNumberStyle.docx");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 2.");
builder->InsertBreak(BreakType::PageBreak);
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 3.");
builder->Write(u"Text 4. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 4.");
builder->InsertBreak(BreakType::PageBreak);
builder->Write(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 2.");
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 3.");
builder->Write(u"Text 4. ");
builder->InsertFootnote(FootnoteType::Endnote, u"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_EQ(doc->get_FootnoteOptions()->get_RestartRule(), FootnoteNumberingRule::Default);
ASSERT_EQ(FootnoteNumberingRule::Default, FootnoteNumberingRule::Continuous);
// We can use the "RestartRule" property to get the document to restart
// the footnote/endnote counts at a new page or section.
doc->get_FootnoteOptions()->set_RestartRule(FootnoteNumberingRule::RestartPage);
doc->get_EndnoteOptions()->set_RestartRule(FootnoteNumberingRule::RestartSection);
doc->Save(ArtifactsDir + u"InlineStory.NumberingRule.docx");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 2.");
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Footnote, u"Footnote 3.");
builder->InsertParagraph();
builder->Write(u"Text 1. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 1.");
builder->Write(u"Text 2. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 2.");
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Endnote, u"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_EQ(1, doc->get_FootnoteOptions()->get_StartNumber());
ASSERT_EQ(1, doc->get_EndnoteOptions()->get_StartNumber());
// We can use the "StartNumber" property to get the document to
// begin a footnote or endnote count at a different number.
doc->get_EndnoteOptions()->set_NumberStyle(NumberStyle::Arabic);
doc->get_EndnoteOptions()->set_StartNumber(50);
doc->Save(ArtifactsDir + u"InlineStory.StartNumber.docx");

◆ get_Frameset()

System::SharedPtr<Aspose::Words::Framesets::Frameset> Aspose::Words::Document::get_Frameset ( ) const

Returns a Frameset instance if this document represents a frames page.

◆ get_GlossaryDocument()

System::SharedPtr<Aspose::Words::BuildingBlocks::GlossaryDocument> Aspose::Words::Document::get_GlossaryDocument ( ) const

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.

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

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

See also
Aspose::Words::BuildingBlocks::GlossaryDocument
Examples

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

void CreateAndInsert()
{
// A document's glossary document stores building blocks.
auto doc = MakeObject<Document>();
auto glossaryDoc = MakeObject<GlossaryDocument>();
doc->set_GlossaryDocument(glossaryDoc);
// Create a building block, name it, and then add it to the glossary document.
auto block = MakeObject<BuildingBlock>(glossaryDoc);
block->set_Name(u"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_EQ(u"00000000-0000-0000-0000-000000000000", System::ObjectExt::ToString(block->get_Guid()));
block->set_Guid(System::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_EQ(u"(Empty Category)", block->get_Category());
ASSERT_EQ(BuildingBlockType::None, block->get_Type());
ASSERT_EQ(BuildingBlockGallery::All, block->get_Gallery());
ASSERT_EQ(BuildingBlockBehavior::Content, block->get_Behavior());
// 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.
auto visitor = MakeObject<ExBuildingBlocks::BuildingBlockVisitor>(glossaryDoc);
block->Accept(visitor);
// We can access the block that we just made from the glossary document.
SharedPtr<BuildingBlock> customBlock = glossaryDoc->GetBuildingBlock(BuildingBlockGallery::QuickParts, u"My custom building blocks", u"Custom Block");
// The block itself is a section that contains the text.
ASSERT_EQ(String::Format(u"Text inside {0}\f", customBlock->get_Name()), customBlock->get_FirstSection()->get_Body()->get_FirstParagraph()->GetText());
ASPOSE_ASSERT_EQ(customBlock->get_FirstSection(), customBlock->get_LastSection());
std::function<void()> parseGuid = [&customBlock]()
{
};
// Now, we can insert it into the document as a new section.
doc->AppendChild(doc->ImportNode(customBlock->get_FirstSection(), true));
// We can also find it in Microsoft Word's Building Blocks Organizer and place it manually.
doc->Save(ArtifactsDir + u"BuildingBlocks.CreateAndInsert.dotx");
}
class BuildingBlockVisitor : public DocumentVisitor
{
public:
BuildingBlockVisitor(SharedPtr<GlossaryDocument> ownerGlossaryDoc)
{
mBuilder = MakeObject<System::Text::StringBuilder>();
mGlossaryDoc = ownerGlossaryDoc;
}
VisitorAction VisitBuildingBlockStart(SharedPtr<BuildingBlock> block) override
{
// Configure the building block as a quick part, and add properties used by Building Blocks Organizer.
block->set_Behavior(BuildingBlockBehavior::Paragraph);
block->set_Category(u"My custom building blocks");
block->set_Description(u"Using this block in the Quick Parts section of word will place its contents at the cursor.");
block->set_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.
auto section = MakeObject<Section>(mGlossaryDoc);
block->AppendChild(section);
block->get_FirstSection()->EnsureMinimum();
auto run = MakeObject<Run>(mGlossaryDoc, String(u"Text inside ") + block->get_Name());
block->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(run);
}
VisitorAction VisitBuildingBlockEnd(SharedPtr<BuildingBlock> block) override
{
mBuilder->Append(String(u"Visited ") + block->get_Name() + u"\r\n");
}
private:
SharedPtr<System::Text::StringBuilder> mBuilder;
SharedPtr<GlossaryDocument> mGlossaryDoc;
};

◆ get_GrammarChecked()

bool Aspose::Words::Document::get_GrammarChecked ( )

Returns true if the document has been checked for grammar.

Examples

Shows how to set spelling or grammar verifying.

auto doc = MakeObject<Document>();
// The string with spelling errors.
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->Add(MakeObject<Run>(doc, u"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->set_SpellingChecked(checkSpellingGrammar);
doc->set_GrammarChecked(checkSpellingGrammar);
doc->Save(ArtifactsDir + u"Document.SpellingOrGrammar.docx");

◆ get_HasMacros()

bool Aspose::Words::Document::get_HasMacros ( )

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

See also
Aspose::Words::Document::RemoveMacros
Examples

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

auto doc = MakeObject<Document>(MyDir + u"Macro.docm");
auto builder = MakeObject<DocumentBuilder>(doc);
ASSERT_TRUE(doc->get_HasMacros());
// Insert a MACROBUTTON field, and reference one of the document's macros by name in the MacroName property.
auto field = System::DynamicCast<FieldMacroButton>(builder->InsertField(FieldType::FieldMacroButton, true));
field->set_MacroName(u"MyMacro");
field->set_DisplayText(String(u"Double click to run macro: ") + field->get_MacroName());
ASSERT_EQ(u" MACROBUTTON MyMacro Double click to run macro: MyMacro", field->GetFieldCode());
// 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 = System::DynamicCast<FieldMacroButton>(builder->InsertField(FieldType::FieldMacroButton, true));
field->set_MacroName(u"ViewZoom200");
field->set_DisplayText(String(u"Run ") + field->get_MacroName());
ASSERT_EQ(u" MACROBUTTON ViewZoom200 Run ViewZoom200", field->GetFieldCode());
// Save the document as a macro-enabled document type.
doc->Save(ArtifactsDir + u"Field.MACROBUTTON.docm");

◆ get_HasRevisions()

bool Aspose::Words::Document::get_HasRevisions ( )

Returns true if the document has any tracked changes.

Examples

Shows how to work with revisions in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Normal editing of the document does not count as a revision.
builder->Write(u"This does not count as a revision. ");
ASSERT_FALSE(doc->get_HasRevisions());
// To register our edits as revisions, we need to declare an author, and then start tracking them.
doc->StartTrackRevisions(u"John Doe", System::DateTime::get_Now());
builder->Write(u"This is revision #1. ");
ASSERT_TRUE(doc->get_HasRevisions());
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
// 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_FALSE(doc->get_TrackRevisions());
// We have added text using the document builder, so the first revision is an insertion-type revision.
SharedPtr<Revision> revision = doc->get_Revisions()->idx_get(0);
ASSERT_EQ(u"John Doe", revision->get_Author());
ASSERT_EQ(u"This is revision #1. ", revision->get_ParentNode()->GetText());
ASSERT_EQ(RevisionType::Insertion, revision->get_RevisionType());
ASSERT_EQ(revision->get_DateTime().get_Date(), System::DateTime::get_Now().get_Date());
ASPOSE_ASSERT_EQ(doc->get_Revisions()->get_Groups()->idx_get(0), revision->get_Group());
// Remove a run to create a deletion-type revision.
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)->Remove();
// Adding a new revision places it at the beginning of the revision collection.
ASSERT_EQ(RevisionType::Deletion, doc->get_Revisions()->idx_get(0)->get_RevisionType());
ASSERT_EQ(2, doc->get_Revisions()->get_Count());
// 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_EQ(u"This does not count as a revision. This is revision #1.", doc->GetText().Trim());
// Accepting the delete revision will remove its parent node from the paragraph text
// and then remove the collection's revision itself.
doc->get_Revisions()->idx_get(0)->Accept();
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #1.", doc->GetText().Trim());
builder->Writeln(u"");
builder->Write(u"This is revision #2.");
// Now move the node to create a moving revision type.
SharedPtr<Node> node = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(1);
SharedPtr<Node> endNode = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(1)->get_NextSibling();
SharedPtr<Node> referenceNode = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0);
while (node != endNode)
{
SharedPtr<Node> nextNode = node->get_NextSibling();
doc->get_FirstSection()->get_Body()->InsertBefore(node, referenceNode);
node = nextNode;
}
ASSERT_EQ(RevisionType::Moving, doc->get_Revisions()->idx_get(0)->get_RevisionType());
ASSERT_EQ(8, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #2.\rThis is revision #1. \rThis is revision #2.", doc->GetText().Trim());
// The moving revision is now at index 1. Reject the revision to discard its contents.
doc->get_Revisions()->idx_get(1)->Reject();
ASSERT_EQ(6, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #1. \rThis is revision #2.", doc->GetText().Trim());

◆ get_HyphenationOptions()

System::SharedPtr<Aspose::Words::Settings::HyphenationOptions> Aspose::Words::Document::get_HyphenationOptions ( )

Provides access to document hyphenation options.

Examples

Shows how to configure automatic hyphenation.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Size(24);
builder->Writeln(String(u"Lorem ipsum dolor sit amet, consectetur adipiscing elit, ") +
u"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
doc->get_HyphenationOptions()->set_AutoHyphenation(true);
doc->get_HyphenationOptions()->set_ConsecutiveHyphenLimit(2);
doc->get_HyphenationOptions()->set_HyphenationZone(720);
doc->get_HyphenationOptions()->set_HyphenateCaps(true);
doc->Save(ArtifactsDir + u"Document.HyphenationOptions.docx");

◆ get_LastSection()

System::SharedPtr<Aspose::Words::Section> Aspose::Words::Document::get_LastSection ( )

Gets the last section in the document.

Examples

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

auto doc = MakeObject<Document>();
// A blank document contains one section by default,
// which contains child nodes that we can edit.
ASSERT_EQ(1, doc->get_Sections()->get_Count());
// Use a document builder to add text to the first section.
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world!");
// Create a second section by inserting a section break.
builder->InsertBreak(BreakType::SectionBreakNewPage);
ASSERT_EQ(2, doc->get_Sections()->get_Count());
// 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->get_LastSection()->get_PageSetup()->get_TextColumns()->SetCount(2);
builder->Writeln(u"Column 1.");
builder->InsertBreak(BreakType::ColumnBreak);
builder->Writeln(u"Column 2.");
ASSERT_EQ(1, doc->get_FirstSection()->get_PageSetup()->get_TextColumns()->get_Count());
ASSERT_EQ(2, doc->get_LastSection()->get_PageSetup()->get_TextColumns()->get_Count());
doc->Save(ArtifactsDir + u"Section.Create.docx");

◆ get_LayoutOptions()

System::SharedPtr<Aspose::Words::Layout::LayoutOptions> Aspose::Words::Document::get_LayoutOptions ( ) const

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

Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a revision, then change the color of all revisions to green.
builder->Writeln(u"This is not a revision.");
doc->StartTrackRevisions(u"John Doe", System::DateTime::get_Now());
builder->Writeln(u"This is a revision.");
doc->StopTrackRevisions();
builder->Writeln(u"This is not a revision.");
// Remove the bar that appears to the left of every revised line.
doc->get_LayoutOptions()->get_RevisionOptions()->set_InsertedTextColor(RevisionColor::BrightGreen);
doc->get_LayoutOptions()->get_RevisionOptions()->set_ShowRevisionBars(false);
doc->Save(ArtifactsDir + u"Document.LayoutOptionsRevisions.pdf");

Shows how to hide text in a rendered output document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert hidden text, then specify whether we wish to omit it from a rendered document.
builder->Writeln(u"This text is not hidden.");
builder->get_Font()->set_Hidden(true);
builder->Writeln(u"This text is hidden.");
doc->get_LayoutOptions()->set_ShowHiddenText(showHiddenText);
doc->Save(ArtifactsDir + u"Document.LayoutOptionsHiddenText.pdf");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"Hello world!");
builder->Writeln(u"Hello again!");
doc->get_LayoutOptions()->set_ShowParagraphMarks(showParagraphMarks);
doc->Save(ArtifactsDir + u"Document.LayoutOptionsParagraphMarks.pdf");

◆ get_MailMerge()

System::SharedPtr<Aspose::Words::MailMerging::MailMerge> Aspose::Words::Document::get_MailMerge ( )

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

◆ get_MailMergeSettings()

System::SharedPtr<Aspose::Words::Settings::MailMergeSettings> Aspose::Words::Document::get_MailMergeSettings ( )

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

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.

◆ get_NodeType()

Aspose::Words::NodeType Aspose::Words::Document::get_NodeType ( ) const
overridevirtual

Returns NodeType.Document.

Examples

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

void RecurseChildren()
{
auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
// Any node that can contain child nodes, such as the document itself, is composite.
ASSERT_TRUE(doc->get_IsComposite());
// Invoke the recursive function that will go through and print all the child nodes of a composite node.
TraverseAllNodes(doc, 0);
}
void TraverseAllNodes(SharedPtr<CompositeNode> parentNode, int depth)
{
for (SharedPtr<Node> childNode = parentNode->get_FirstChild(); childNode != nullptr; childNode = childNode->get_NextSibling())
{
std::cout << (String(u'\t', depth)) << Node::NodeTypeToString(childNode->get_NodeType());
// Recurse into the node if it is a composite node. Otherwise, print its contents if it is an inline node.
if (childNode->get_IsComposite())
{
std::cout << std::endl;
TraverseAllNodes(System::DynamicCast<CompositeNode>(childNode), depth + 1);
}
else if (System::ObjectExt::Is<Inline>(childNode))
{
std::cout << " - \"" << childNode->GetText().Trim() << "\"" << std::endl;
}
else
{
std::cout << std::endl;
}
}
}

Implements Aspose::Words::Node.

◆ get_OriginalFileName()

System::String Aspose::Words::Document::get_OriginalFileName ( ) const

Gets the original file name of the document.

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

Examples

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

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
ASSERT_EQ(MyDir + u"Document.docx", doc->get_OriginalFileName());
ASSERT_EQ(LoadFormat::Docx, doc->get_OriginalLoadFormat());

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.
{
SharedPtr<System::IO::FileStream> docStream = System::IO::File::OpenRead(MyDir + u"Word document with missing file extension");
SharedPtr<FileFormatInfo> info = FileFormatUtil::DetectFileFormat(docStream);
LoadFormat loadFormat = info->get_LoadFormat();
ASSERT_EQ(LoadFormat::Doc, loadFormat);
// 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);
// 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.
auto doc = MakeObject<Document>(docStream);
ASSERT_EQ(u".doc", FileFormatUtil::SaveFormatToExtension(saveFormat));
doc->Save(ArtifactsDir + u"File.SaveToDetectedFileFormat" + FileFormatUtil::SaveFormatToExtension(saveFormat));
}

◆ get_OriginalLoadFormat()

Aspose::Words::LoadFormat Aspose::Words::Document::get_OriginalLoadFormat ( ) const

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

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

Examples

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

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
ASSERT_EQ(MyDir + u"Document.docx", doc->get_OriginalFileName());
ASSERT_EQ(LoadFormat::Docx, doc->get_OriginalLoadFormat());

◆ get_PackageCustomParts()

System::SharedPtr<Aspose::Words::Markup::CustomPartCollection> Aspose::Words::Document::get_PackageCustomParts ( ) const

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

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

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

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

This property cannot be null.

See also
Aspose::Words::Markup::CustomPart
Examples

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

auto doc = MakeObject<Document>(MyDir + u"Custom parts OOXML package.docx");
ASSERT_EQ(2, doc->get_PackageCustomParts()->get_Count());
// Clone the second part, then add the clone to the collection.
SharedPtr<CustomPart> clonedPart = doc->get_PackageCustomParts()->idx_get(1)->Clone();
doc->get_PackageCustomParts()->Add(clonedPart);
ASSERT_EQ(3, doc->get_PackageCustomParts()->get_Count());
// Enumerate over the collection and print every part.
{
SharedPtr<System::Collections::Generic::IEnumerator<SharedPtr<CustomPart>>> enumerator = doc->get_PackageCustomParts()->GetEnumerator();
int index = 0;
while (enumerator->MoveNext())
{
std::cout << "Part index " << index << ":" << std::endl;
std::cout << "\tName:\t\t\t\t" << enumerator->get_Current()->get_Name() << std::endl;
std::cout << "\tContent type:\t\t" << enumerator->get_Current()->get_ContentType() << std::endl;
std::cout << "\tRelationship type:\t" << enumerator->get_Current()->get_RelationshipType() << std::endl;
std::cout << (enumerator->get_Current()->get_IsExternal()
? u"\tSourced from outside the document"
: String::Format(u"\tStored within the document, length: {0} bytes", enumerator->get_Current()->get_Data()->get_Length()))
<< std::endl;
index++;
}
}
// We can remove elements from this collection individually, or all at once.
doc->get_PackageCustomParts()->RemoveAt(2);
ASSERT_EQ(2, doc->get_PackageCustomParts()->get_Count());
doc->get_PackageCustomParts()->Clear();
ASSERT_EQ(0, doc->get_PackageCustomParts()->get_Count());

◆ get_PageCount()

int32_t Aspose::Words::Document::get_PageCount ( )

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

See also
Aspose::Words::Document::UpdatePageLayout
Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"Page 1");
builder->InsertBreak(BreakType::PageBreak);
builder->Write(u"Page 2");
builder->InsertBreak(BreakType::PageBreak);
builder->Write(u"Page 3");
// Verify the expected page count of the document.
ASSERT_EQ(3, doc->get_PageCount());
// 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 + u"Document.GetPageCount.pdf");

◆ get_ProtectionType()

Aspose::Words::ProtectionType Aspose::Words::Document::get_ProtectionType ( )

Gets the currently active document protection type.

This property allows to retrieve the currently set document protection type. To change the document protection type use the Protect() and Unprotect methods.

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

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

See also
Aspose::Words::Document::Protect(Aspose::Words::ProtectionType, System::String)
Aspose::Words::Document::Unprotect
Aspose::Words::Document::get_WriteProtection
Examples

Shows how to protect and unprotect a document.

auto doc = MakeObject<Document>();
doc->Protect(ProtectionType::ReadOnly, u"password");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
// 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 + u"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.
auto protectedDoc = MakeObject<Document>(ArtifactsDir + u"Document.Protect.docx");
ASSERT_EQ(ProtectionType::ReadOnly, protectedDoc->get_ProtectionType());
auto builder = MakeObject<DocumentBuilder>(protectedDoc);
builder->Writeln(u"Text added to a protected document.");
// There are two ways of removing protection from a document.
// 1 - With no password:
doc->Unprotect();
ASSERT_EQ(ProtectionType::NoProtection, doc->get_ProtectionType());
doc->Protect(ProtectionType::ReadOnly, u"NewPassword");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
doc->Unprotect(u"WrongPassword");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
// 2 - With the correct password:
doc->Unprotect(u"NewPassword");
ASSERT_EQ(ProtectionType::NoProtection, doc->get_ProtectionType());

◆ get_RemovePersonalInformation()

bool Aspose::Words::Document::get_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.

Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert some content with personal information.
doc->get_BuiltInDocumentProperties()->set_Author(u"John Doe");
doc->get_BuiltInDocumentProperties()->set_Company(u"Placeholder Inc.");
doc->StartTrackRevisions(doc->get_BuiltInDocumentProperties()->get_Author(), System::DateTime::get_Now());
builder->Write(u"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->set_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 + u"Document.RemovePersonalInformation.docx");
doc = MakeObject<Document>(ArtifactsDir + u"Document.RemovePersonalInformation.docx");
ASPOSE_ASSERT_EQ(saveWithoutPersonalInfo, doc->get_RemovePersonalInformation());
ASSERT_EQ(u"John Doe", doc->get_BuiltInDocumentProperties()->get_Author());
ASSERT_EQ(u"Placeholder Inc.", doc->get_BuiltInDocumentProperties()->get_Company());
ASSERT_EQ(u"John Doe", doc->get_Revisions()->idx_get(0)->get_Author());

◆ get_Revisions()

System::SharedPtr<Aspose::Words::RevisionCollection> Aspose::Words::Document::get_Revisions ( )

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

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.

Examples

Shows how to work with revisions in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Normal editing of the document does not count as a revision.
builder->Write(u"This does not count as a revision. ");
ASSERT_FALSE(doc->get_HasRevisions());
// To register our edits as revisions, we need to declare an author, and then start tracking them.
doc->StartTrackRevisions(u"John Doe", System::DateTime::get_Now());
builder->Write(u"This is revision #1. ");
ASSERT_TRUE(doc->get_HasRevisions());
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
// 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_FALSE(doc->get_TrackRevisions());
// We have added text using the document builder, so the first revision is an insertion-type revision.
SharedPtr<Revision> revision = doc->get_Revisions()->idx_get(0);
ASSERT_EQ(u"John Doe", revision->get_Author());
ASSERT_EQ(u"This is revision #1. ", revision->get_ParentNode()->GetText());
ASSERT_EQ(RevisionType::Insertion, revision->get_RevisionType());
ASSERT_EQ(revision->get_DateTime().get_Date(), System::DateTime::get_Now().get_Date());
ASPOSE_ASSERT_EQ(doc->get_Revisions()->get_Groups()->idx_get(0), revision->get_Group());
// Remove a run to create a deletion-type revision.
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)->Remove();
// Adding a new revision places it at the beginning of the revision collection.
ASSERT_EQ(RevisionType::Deletion, doc->get_Revisions()->idx_get(0)->get_RevisionType());
ASSERT_EQ(2, doc->get_Revisions()->get_Count());
// 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_EQ(u"This does not count as a revision. This is revision #1.", doc->GetText().Trim());
// Accepting the delete revision will remove its parent node from the paragraph text
// and then remove the collection's revision itself.
doc->get_Revisions()->idx_get(0)->Accept();
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #1.", doc->GetText().Trim());
builder->Writeln(u"");
builder->Write(u"This is revision #2.");
// Now move the node to create a moving revision type.
SharedPtr<Node> node = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(1);
SharedPtr<Node> endNode = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(1)->get_NextSibling();
SharedPtr<Node> referenceNode = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0);
while (node != endNode)
{
SharedPtr<Node> nextNode = node->get_NextSibling();
doc->get_FirstSection()->get_Body()->InsertBefore(node, referenceNode);
node = nextNode;
}
ASSERT_EQ(RevisionType::Moving, doc->get_Revisions()->idx_get(0)->get_RevisionType());
ASSERT_EQ(8, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #2.\rThis is revision #1. \rThis is revision #2.", doc->GetText().Trim());
// The moving revision is now at index 1. Reject the revision to discard its contents.
doc->get_Revisions()->idx_get(1)->Reject();
ASSERT_EQ(6, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #1. \rThis is revision #2.", doc->GetText().Trim());

◆ get_RevisionsView()

Aspose::Words::RevisionsView Aspose::Words::Document::get_RevisionsView ( ) const

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

Examples

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

auto doc = MakeObject<Document>(MyDir + u"Revisions at list levels.docx");
doc->UpdateListLabels();
SharedPtr<ParagraphCollection> paragraphs = doc->get_FirstSection()->get_Body()->get_Paragraphs();
ASSERT_EQ(u"1.", paragraphs->idx_get(0)->get_ListLabel()->get_LabelString());
ASSERT_EQ(u"a.", paragraphs->idx_get(1)->get_ListLabel()->get_LabelString());
ASSERT_EQ(String::Empty, paragraphs->idx_get(2)->get_ListLabel()->get_LabelString());
// View the document object as if all the revisions are accepted. Currently supports list labels.
doc->set_RevisionsView(RevisionsView::Final);
ASSERT_EQ(String::Empty, paragraphs->idx_get(0)->get_ListLabel()->get_LabelString());
ASSERT_EQ(u"1.", paragraphs->idx_get(1)->get_ListLabel()->get_LabelString());
ASSERT_EQ(u"a.", paragraphs->idx_get(2)->get_ListLabel()->get_LabelString());

◆ get_Sections()

System::SharedPtr<Aspose::Words::SectionCollection> Aspose::Words::Document::get_Sections ( )

Returns a collection that represents all sections in the document.

Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"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(u"This text is in section 2.");
ASSERT_EQ(SectionStart::NewPage, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_SectionStart());
// 2 - Starts the next section on the current page:
builder->InsertBreak(BreakType::SectionBreakContinuous);
builder->Writeln(u"This text is in section 3.");
ASSERT_EQ(SectionStart::Continuous, doc->get_Sections()->idx_get(2)->get_PageSetup()->get_SectionStart());
// 3 - Starts the next section on a new even page:
builder->InsertBreak(BreakType::SectionBreakEvenPage);
builder->Writeln(u"This text is in section 4.");
ASSERT_EQ(SectionStart::EvenPage, doc->get_Sections()->idx_get(3)->get_PageSetup()->get_SectionStart());
// 4 - Starts the next section on a new odd page:
builder->InsertBreak(BreakType::SectionBreakOddPage);
builder->Writeln(u"This text is in section 5.");
ASSERT_EQ(SectionStart::OddPage, doc->get_Sections()->idx_get(4)->get_PageSetup()->get_SectionStart());
// 5 - Starts the next section on a new column:
SharedPtr<TextColumnCollection> columns = builder->get_PageSetup()->get_TextColumns();
columns->SetCount(2);
builder->InsertBreak(BreakType::SectionBreakNewColumn);
builder->Writeln(u"This text is in section 6.");
ASSERT_EQ(SectionStart::NewColumn, doc->get_Sections()->idx_get(5)->get_PageSetup()->get_SectionStart());
doc->Save(ArtifactsDir + u"PageSetup.SetSectionStart.docx");

Shows how to add and remove sections in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"Section 1");
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->Write(u"Section 2");
ASSERT_EQ(u"Section 1\x000c"
u"Section 2",
doc->GetText().Trim());
// Delete the first section from the document.
doc->get_Sections()->RemoveAt(0);
ASSERT_EQ(u"Section 2", doc->GetText().Trim());
// Append a copy of what is now the first section to the end of the document.
int lastSectionIdx = doc->get_Sections()->get_Count() - 1;
SharedPtr<Section> newSection = doc->get_Sections()->idx_get(lastSectionIdx)->Clone();
doc->get_Sections()->Add(newSection);
ASSERT_EQ(u"Section 2\x000c"
u"Section 2",
doc->GetText().Trim());

◆ get_ShadeFormData()

bool Aspose::Words::Document::get_ShadeFormData ( )

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

Examples

Shows how to apply gray shading to form fields.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"Hello world! ");
builder->InsertTextInput(u"My form field", TextFormFieldType::Regular, u"", u"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->set_ShadeFormData(useGreyShading);
doc->Save(ArtifactsDir + u"Document.ShadeFormData.docx");

◆ get_ShowGrammaticalErrors()

bool Aspose::Words::Document::get_ShowGrammaticalErrors ( )

Specifies whether to display grammar errors in this document.

Examples

Shows how to show/hide errors in the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert two sentences with mistakes that would be picked up
// by the spelling and grammar checkers in Microsoft Word.
builder->Writeln(u"There is a speling error in this sentence.");
builder->Writeln(u"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->set_ShowGrammaticalErrors(showErrors);
doc->set_ShowSpellingErrors(showErrors);
doc->Save(ArtifactsDir + u"Document.SpellingAndGrammarErrors.docx");

◆ get_ShowSpellingErrors()

bool Aspose::Words::Document::get_ShowSpellingErrors ( )

Specifies whether to display spelling errors in this document.

Examples

Shows how to show/hide errors in the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert two sentences with mistakes that would be picked up
// by the spelling and grammar checkers in Microsoft Word.
builder->Writeln(u"There is a speling error in this sentence.");
builder->Writeln(u"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->set_ShowGrammaticalErrors(showErrors);
doc->set_ShowSpellingErrors(showErrors);
doc->Save(ArtifactsDir + u"Document.SpellingAndGrammarErrors.docx");

◆ get_SpellingChecked()

bool Aspose::Words::Document::get_SpellingChecked ( )

Returns true if the document has been checked for spelling.

Examples

Shows how to set spelling or grammar verifying.

auto doc = MakeObject<Document>();
// The string with spelling errors.
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->Add(MakeObject<Run>(doc, u"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->set_SpellingChecked(checkSpellingGrammar);
doc->set_GrammarChecked(checkSpellingGrammar);
doc->Save(ArtifactsDir + u"Document.SpellingOrGrammar.docx");

◆ get_Theme()

System::SharedPtr<Aspose::Words::Themes::Theme> Aspose::Words::Document::get_Theme ( )

Gets the Theme object for this document.

Examples

Shows how to set custom colors and fonts for themes.

auto doc = MakeObject<Document>(MyDir + u"Theme colors.docx");
// The "Theme" object gives us access to the document theme, a source of default fonts and colors.
SharedPtr<Theme> theme = doc->get_Theme();
// Some styles, such as "Heading 1" and "Subtitle", will inherit these fonts.
theme->get_MajorFonts()->set_Latin(u"Courier New");
theme->get_MinorFonts()->set_Latin(u"Agency FB");
// Other languages may also have their custom fonts in this theme.
ASSERT_EQ(String::Empty, theme->get_MajorFonts()->get_ComplexScript());
ASSERT_EQ(String::Empty, theme->get_MajorFonts()->get_EastAsian());
ASSERT_EQ(String::Empty, theme->get_MinorFonts()->get_ComplexScript());
ASSERT_EQ(String::Empty, theme->get_MinorFonts()->get_EastAsian());
// 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".
SharedPtr<ThemeColors> colors = theme->get_Colors();
colors->set_Light2(System::Drawing::Color::get_Khaki());
colors->set_Accent3(System::Drawing::Color::get_Yellow());
colors->set_Accent4(System::Drawing::Color::get_Gold());
// Apply custom colors to hyperlinks in their clicked and un-clicked states.
colors->set_Hyperlink(System::Drawing::Color::get_Black());
colors->set_FollowedHyperlink(System::Drawing::Color::get_Gray());
doc->Save(ArtifactsDir + u"Themes.CustomColorsAndFonts.docx");

◆ get_TrackRevisions()

bool Aspose::Words::Document::get_TrackRevisions ( )

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

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

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

Examples

Shows how to work with revisions in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Normal editing of the document does not count as a revision.
builder->Write(u"This does not count as a revision. ");
ASSERT_FALSE(doc->get_HasRevisions());
// To register our edits as revisions, we need to declare an author, and then start tracking them.
doc->StartTrackRevisions(u"John Doe", System::DateTime::get_Now());
builder->Write(u"This is revision #1. ");
ASSERT_TRUE(doc->get_HasRevisions());
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
// 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_FALSE(doc->get_TrackRevisions());
// We have added text using the document builder, so the first revision is an insertion-type revision.
SharedPtr<Revision> revision = doc->get_Revisions()->idx_get(0);
ASSERT_EQ(u"John Doe", revision->get_Author());
ASSERT_EQ(u"This is revision #1. ", revision->get_ParentNode()->GetText());
ASSERT_EQ(RevisionType::Insertion, revision->get_RevisionType());
ASSERT_EQ(revision->get_DateTime().get_Date(), System::DateTime::get_Now().get_Date());
ASPOSE_ASSERT_EQ(doc->get_Revisions()->get_Groups()->idx_get(0), revision->get_Group());
// Remove a run to create a deletion-type revision.
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)->Remove();
// Adding a new revision places it at the beginning of the revision collection.
ASSERT_EQ(RevisionType::Deletion, doc->get_Revisions()->idx_get(0)->get_RevisionType());
ASSERT_EQ(2, doc->get_Revisions()->get_Count());
// 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_EQ(u"This does not count as a revision. This is revision #1.", doc->GetText().Trim());
// Accepting the delete revision will remove its parent node from the paragraph text
// and then remove the collection's revision itself.
doc->get_Revisions()->idx_get(0)->Accept();
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #1.", doc->GetText().Trim());
builder->Writeln(u"");
builder->Write(u"This is revision #2.");
// Now move the node to create a moving revision type.
SharedPtr<Node> node = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(1);
SharedPtr<Node> endNode = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(1)->get_NextSibling();
SharedPtr<Node> referenceNode = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0);
while (node != endNode)
{
SharedPtr<Node> nextNode = node->get_NextSibling();
doc->get_FirstSection()->get_Body()->InsertBefore(node, referenceNode);
node = nextNode;
}
ASSERT_EQ(RevisionType::Moving, doc->get_Revisions()->idx_get(0)->get_RevisionType());
ASSERT_EQ(8, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #2.\rThis is revision #1. \rThis is revision #2.", doc->GetText().Trim());
// The moving revision is now at index 1. Reject the revision to discard its contents.
doc->get_Revisions()->idx_get(1)->Reject();
ASSERT_EQ(6, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"This is revision #1. \rThis is revision #2.", doc->GetText().Trim());

◆ get_Variables()

System::SharedPtr<Aspose::Words::VariableCollection> Aspose::Words::Document::get_Variables ( )

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

Examples

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

auto doc = MakeObject<Document>();
SharedPtr<VariableCollection> variables = doc->get_Variables();
// Every document has a collection of key/value pair variables, which we can add items to.
variables->Add(u"Home address", u"123 Main St.");
variables->Add(u"City", u"London");
variables->Add(u"Bedrooms", u"3");
ASSERT_EQ(3, variables->get_Count());
// We can display the values of variables in the document body using DOCVARIABLE fields.
auto builder = MakeObject<DocumentBuilder>(doc);
auto field = System::DynamicCast<FieldDocVariable>(builder->InsertField(FieldType::FieldDocVariable, true));
field->set_VariableName(u"Home address");
field->Update();
ASSERT_EQ(u"123 Main St.", field->get_Result());
// Assigning values to existing keys will update them.
variables->Add(u"Home address", u"456 Queen St.");
// We will then have to update DOCVARIABLE fields to ensure they display an up-to-date value.
ASSERT_EQ(u"123 Main St.", field->get_Result());
field->Update();
ASSERT_EQ(u"456 Queen St.", field->get_Result());
// Verify that the document variables with a certain name or value exist.
ASSERT_TRUE(variables->Contains(u"City"));
ASSERT_TRUE(variables->LINQ_Any([](auto v) { return v.get_Value() == u"London"; }));
// The collection of variables automatically sorts variables alphabetically by name.
ASSERT_EQ(0, variables->IndexOfKey(u"Bedrooms"));
ASSERT_EQ(1, variables->IndexOfKey(u"City"));
ASSERT_EQ(2, variables->IndexOfKey(u"Home address"));
// Enumerate over the collection of variables.
{
SharedPtr<System::Collections::Generic::IEnumerator<System::Collections::Generic::KeyValuePair<String, String>>> enumerator =
doc->get_Variables()->GetEnumerator();
while (enumerator->MoveNext())
{
std::cout << "Name: " << enumerator->get_Current().get_Key() << ", Value: " << enumerator->get_Current().get_Value() << std::endl;
}
}
// Below are three ways of removing document variables from a collection.
// 1 - By name:
variables->Remove(u"City");
ASSERT_FALSE(variables->Contains(u"City"));
// 2 - By index:
variables->RemoveAt(1);
ASSERT_FALSE(variables->Contains(u"Home address"));
// 3 - Clear the whole collection at once:
variables->Clear();
ASSERT_EQ(0, variables->get_Count());

◆ get_VbaProject()

System::SharedPtr<Aspose::Words::Vba::VbaProject> Aspose::Words::Document::get_VbaProject ( ) const

Gets or sets a VbaProject.

Examples

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

auto doc = MakeObject<Document>(MyDir + u"VBA project.docm");
// A VBA project contains a collection of VBA modules.
SharedPtr<VbaProject> vbaProject = doc->get_VbaProject();
std::cout << (vbaProject->get_IsSigned() ? String::Format(u"Project name: {0} signed; Project code page: {1}; Modules count: {2}\n",
vbaProject->get_Name(), vbaProject->get_CodePage(), vbaProject->get_Modules()->LINQ_Count())
: String::Format(u"Project name: {0} not signed; Project code page: {1}; Modules count: {2}\n",
vbaProject->get_Name(), vbaProject->get_CodePage(), vbaProject->get_Modules()->LINQ_Count()))
<< std::endl;
SharedPtr<VbaModuleCollection> vbaModules = doc->get_VbaProject()->get_Modules();
ASSERT_EQ(vbaModules->LINQ_Count(), 3);
for (const auto& module_ : vbaModules)
{
std::cout << "Module name: " << module_->get_Name() << ";\nModule code:\n" << module_->get_SourceCode() << "\n" << std::endl;
}
// Set new source code for VBA module. You can access VBA modules in the collection either by index or by name.
vbaModules->idx_get(0)->set_SourceCode(u"Your VBA code...");
vbaModules->idx_get(u"Module1")->set_SourceCode(u"Your VBA code...");
// Remove a module from the collection.
vbaModules->Remove(vbaModules->idx_get(2));

◆ get_VersionsCount()

int32_t Aspose::Words::Document::get_VersionsCount ( )

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

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.

Examples

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

auto doc = MakeObject<Document>(MyDir + u"Versions.doc");
// We can read this property of a document, but we cannot preserve it while saving.
ASSERT_EQ(4, doc->get_VersionsCount());
doc->Save(ArtifactsDir + u"Document.VersionsCount.doc");
doc = MakeObject<Document>(ArtifactsDir + u"Document.VersionsCount.doc");
ASSERT_EQ(0, doc->get_VersionsCount());

◆ get_ViewOptions()

System::SharedPtr<Aspose::Words::Settings::ViewOptions> Aspose::Words::Document::get_ViewOptions ( )

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

Examples

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world!");
doc->get_ViewOptions()->set_ViewType(ViewType::PageLayout);
doc->get_ViewOptions()->set_ZoomPercent(50);
ASSERT_EQ(ZoomType::Custom, doc->get_ViewOptions()->get_ZoomType());
ASSERT_EQ(ZoomType::None, doc->get_ViewOptions()->get_ZoomType());
doc->Save(ArtifactsDir + u"ViewOptions.SetZoomPercentage.doc");

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

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"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->get_ViewOptions()->set_ZoomType(zoomType);
doc->Save(ArtifactsDir + u"ViewOptions.SetZoomType.doc");

◆ get_Watermark()

System::SharedPtr<Aspose::Words::Watermark> Aspose::Words::Document::get_Watermark ( )

Provides access to the document watermark.

◆ get_WebExtensionTaskPanes()

System::SharedPtr<Aspose::Words::WebExtensions::TaskPaneCollection> Aspose::Words::Document::get_WebExtensionTaskPanes ( ) const

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

◆ get_WriteProtection()

System::SharedPtr<Aspose::Words::Settings::WriteProtection> Aspose::Words::Document::get_WriteProtection ( )

Provides access to the document write protection options.

Examples

Shows how to protect a document with a password.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world! This document is protected.");
// Enter a password up to 15 characters in length, and then verify the document's protection status.
doc->get_WriteProtection()->SetPassword(u"MyPassword");
doc->get_WriteProtection()->set_ReadOnlyRecommended(true);
ASSERT_TRUE(doc->get_WriteProtection()->get_IsWriteProtected());
ASSERT_TRUE(doc->get_WriteProtection()->ValidatePassword(u"MyPassword"));
// Protection does not prevent the document from being edited programmatically, nor does it encrypt the contents.
doc->Save(ArtifactsDir + u"Document.WriteProtection.docx");
doc = MakeObject<Document>(ArtifactsDir + u"Document.WriteProtection.docx");
ASSERT_TRUE(doc->get_WriteProtection()->get_IsWriteProtected());
builder = MakeObject<DocumentBuilder>(doc);
builder->MoveToDocumentEnd();
builder->Writeln(u"Writing text in a protected document.");
ASSERT_EQ(String(u"Hello world! This document is protected.") + u"\rWriting text in a protected document.", doc->GetText().Trim());

◆ GetPageInfo()

System::SharedPtr<Aspose::Words::Rendering::PageInfo> Aspose::Words::Document::GetPageInfo ( int32_t  pageIndex)

Gets the page size, orientation and other information about a page that might be useful for printing or rendering.

Parameters
pageIndexThe 0-based page index.

◆ GetType()

virtual const System::TypeInfo& Aspose::Words::Document::GetType ( ) const
overridevirtual

Reimplemented from Aspose::Words::DocumentBase.

◆ Is()

virtual bool Aspose::Words::Document::Is ( const System::TypeInfo target) const
overridevirtual

Reimplemented from Aspose::Words::DocumentBase.

◆ JoinRunsWithSameFormatting()

int32_t Aspose::Words::Document::JoinRunsWithSameFormatting ( )

Joins runs with same formatting in all paragraphs of the document.

This is an optimization method. Some documents contain adjacent runs with same formatting. Usually this occurs if a document was intensively edited manually. You can reduce the document size and speed up further processing by joining these runs.

The operation checks every Paragraph node in the document for adjacent Run nodes having identical properties. It ignores unique identifiers used to track editing sessions of run creation and modification. First run in every joining sequence accumulates all text. Remaining runs are deleted from the document.

Returns
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.
auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
// If any number of these runs are adjacent with identical formatting,
// then the document may be simplified.
ASSERT_EQ(317, doc->GetChildNodes(NodeType::Run, true)->get_Count());
// Combine such runs with this method and verify the number of run joins that will take place.
ASSERT_EQ(121, doc->JoinRunsWithSameFormatting());
// 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_EQ(196, doc->GetChildNodes(NodeType::Run, true)->get_Count());

◆ NormalizeFieldTypes()

void Aspose::Words::Document::NormalizeFieldTypes ( )

Changes field type values FieldType of FieldStart, FieldSeparator, FieldEnd in the whole document so that they correspond to the field types contained in the field codes.

Use this method after document changes that affect field types.

To change field type values in a specific part of the document use NormalizeFieldTypes.

Examples

Shows how to get the keep a field's type up to date with its field code.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Field> field = builder->InsertField(u"DATE", nullptr);
// Aspose.Words automatically detects field types based on field codes.
ASSERT_EQ(FieldType::FieldDate, field->get_Type());
// Manually change the raw text of the field, which determines the field code.
auto fieldText = System::DynamicCast<Run>(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Run, true)->idx_get(0));
fieldText->set_Text(u"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_EQ(u"PAGE", field->GetFieldCode());
ASSERT_EQ(FieldType::FieldDate, field->get_Type());
ASSERT_EQ(FieldType::FieldDate, field->get_Start()->get_FieldType());
ASSERT_EQ(FieldType::FieldDate, field->get_Separator()->get_FieldType());
ASSERT_EQ(FieldType::FieldDate, field->get_End()->get_FieldType());
// Update those properties with this method to display current value.
doc->NormalizeFieldTypes();
ASSERT_EQ(FieldType::FieldPage, field->get_Type());
ASSERT_EQ(FieldType::FieldPage, field->get_Start()->get_FieldType());
ASSERT_EQ(FieldType::FieldPage, field->get_Separator()->get_FieldType());
ASSERT_EQ(FieldType::FieldPage, field->get_End()->get_FieldType());

◆ Protect() [1/2]

void Aspose::Words::Document::Protect ( Aspose::Words::ProtectionType  type)

Protects the document from changes without changing the existing password or assigns a random password.

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.

Parameters
typeSpecifies the protection type for the document.
Examples

Shows how to turn off protection for a section.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Section 1. Hello world!");
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->Writeln(u"Section 2. Hello again!");
builder->Write(u"Please enter text here: ");
builder->InsertTextInput(u"TextInput1", TextFormFieldType::Regular, u"", u"Placeholder text", 0);
// Apply write protection to every section in the document.
// Turn off write protection for the first section.
doc->get_Sections()->idx_get(0)->set_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 + u"Section.Protect.docx");

◆ Protect() [2/2]

void Aspose::Words::Document::Protect ( Aspose::Words::ProtectionType  type,
const System::String password 
)

Protects the document from changes and optionally sets a protection password.

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

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

Parameters
typeSpecifies the protection type for the document.
passwordThe 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.

auto doc = MakeObject<Document>();
doc->Protect(ProtectionType::ReadOnly, u"password");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
// 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 + u"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.
auto protectedDoc = MakeObject<Document>(ArtifactsDir + u"Document.Protect.docx");
ASSERT_EQ(ProtectionType::ReadOnly, protectedDoc->get_ProtectionType());
auto builder = MakeObject<DocumentBuilder>(protectedDoc);
builder->Writeln(u"Text added to a protected document.");
// There are two ways of removing protection from a document.
// 1 - With no password:
doc->Unprotect();
ASSERT_EQ(ProtectionType::NoProtection, doc->get_ProtectionType());
doc->Protect(ProtectionType::ReadOnly, u"NewPassword");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
doc->Unprotect(u"WrongPassword");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
// 2 - With the correct password:
doc->Unprotect(u"NewPassword");
ASSERT_EQ(ProtectionType::NoProtection, doc->get_ProtectionType());

◆ RemoveExternalSchemaReferences()

void Aspose::Words::Document::RemoveExternalSchemaReferences ( )

Removes external XML schema references from this document.

Examples

Shows how to remove all external XML schema references from a document.

auto doc = MakeObject<Document>(MyDir + u"External XML schema.docx");
doc->RemoveExternalSchemaReferences();

◆ RemoveMacros()

void Aspose::Words::Document::RemoveMacros ( )

Removes all macros (the VBA project) as well as toolbars and command customizations from the document.

By removing all macros from a document you can ensure the document contains no macro viruses.

Examples

Shows how to remove all macros from a document.

auto doc = MakeObject<Document>(MyDir + u"Macro.docm");
ASSERT_TRUE(doc->get_HasMacros());
ASSERT_EQ(u"Project", doc->get_VbaProject()->get_Name());
// Remove the document's VBA project, along with all its macros.
doc->RemoveMacros();
ASSERT_FALSE(doc->get_HasMacros());
ASSERT_TRUE(doc->get_VbaProject() == nullptr);

◆ RenderToScale()

System::Drawing::SizeF Aspose::Words::Document::RenderToScale ( int32_t  pageIndex,
const System::SharedPtr< System::Drawing::Graphics > &  graphics,
float  x,
float  y,
float  scale 
)

Renders a document page into a object to a specified scale.

Parameters
pageIndexThe 0-based page index.
graphicsThe object where to render to.
xThe X coordinate (in world units) of the top left corner of the rendered page.
yThe Y coordinate (in world units) of the top left corner of the rendered page.
scaleThe scale for rendering the page (1.0 is 100%).
Returns
The width and height (in world units) of the rendered page.
Examples

Shows how to the individual pages of a document to graphics to create one image with thumbnails of all pages.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
// Calculate the number of rows and columns that we will fill with thumbnails.
const int thumbColumns = 2;
int remainder;
int thumbRows = System::Math::DivRem(doc->get_PageCount(), thumbColumns, remainder);
if (remainder > 0)
{
thumbRows++;
}
// Scale the thumbnails relative to the size of the first page.
const float scale = 0.25f;
System::Drawing::Size thumbSize = doc->GetPageInfo(0)->GetSizeInPixels(scale, 96.0f);
// Calculate the size of the image that will contain all the thumbnails.
int imgWidth = thumbSize.get_Width() * thumbColumns;
int imgHeight = thumbSize.get_Height() * thumbRows;
{
auto img = MakeObject<System::Drawing::Bitmap>(imgWidth, imgHeight);
{
SharedPtr<System::Drawing::Graphics> gr = System::Drawing::Graphics::FromImage(img);
// Fill the background, which is transparent by default, in white.
gr->FillRectangle(MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_White()), 0, 0, imgWidth, imgHeight);
for (int pageIndex = 0; pageIndex < doc->get_PageCount(); pageIndex++)
{
int columnIdx;
int rowIdx = System::Math::DivRem(pageIndex, thumbColumns, columnIdx);
// Specify where we want the thumbnail to appear.
float thumbLeft = static_cast<float>(columnIdx * thumbSize.get_Width());
float thumbTop = static_cast<float>(rowIdx * thumbSize.get_Height());
// Render a page as a thumbnail, and then frame it in a rectangle of the same size.
System::Drawing::SizeF size = doc->RenderToScale(pageIndex, gr, thumbLeft, thumbTop, scale);
gr->DrawRectangle(System::Drawing::Pens::get_Black(), thumbLeft, thumbTop, size.get_Width(), size.get_Height());
}
img->Save(ArtifactsDir + u"Rendering.Thumbnails.png");
}
}

◆ RenderToSize()

float Aspose::Words::Document::RenderToSize ( int32_t  pageIndex,
const System::SharedPtr< System::Drawing::Graphics > &  graphics,
float  x,
float  y,
float  width,
float  height 
)

Renders a document page into a object to a specified size.

Parameters
pageIndexThe 0-based page index.
graphicsThe object where to render to.
xThe X coordinate (in world units) of the top left corner of the rendered page.
yThe Y coordinate (in world units) of the top left corner of the rendered page.
widthThe maximum width (in world units) that can be occupied by the rendered page.
heightThe maximum height (in world units) that can be occupied by the rendered page.
Returns
The scale that was automatically calculated for the rendered page to fit the specified size.
Examples

Shows how to render a document to a bitmap at a specified location and size.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
{
auto bmp = MakeObject<System::Drawing::Bitmap>(700, 700);
{
SharedPtr<System::Drawing::Graphics> gr = System::Drawing::Graphics::FromImage(bmp);
// Set the "PageUnit" property to "GraphicsUnit.Inch" to use inches as the
// measurement unit for any transformations and dimensions that we will define.
gr->set_PageUnit(System::Drawing::GraphicsUnit::Inch);
// Offset the output 0.5" from the edge.
gr->TranslateTransform(0.5f, 0.5f);
// Rotate the output by 10 degrees.
gr->RotateTransform(10.0f);
// Draw a 3"x3" rectangle.
gr->DrawRectangle(MakeObject<System::Drawing::Pen>(System::Drawing::Color::get_Black(), 3.f / 72.f), 0.f, 0.f, 3.f, 3.f);
// Draw the first page of our document with the same dimensions and transformation as the rectangle.
// The rectangle will frame the first page.
float returnedScale = doc->RenderToSize(0, gr, 0.f, 0.f, 3.f, 3.f);
// This is the scaling factor that the RenderToSize method applied to the first page to fit the specified size.
ASSERT_NEAR(0.2566f, returnedScale, 0.0001f);
// Set the "PageUnit" property to "GraphicsUnit.Millimeter" to use millimeters as the
// measurement unit for any transformations and dimensions that we will define.
gr->set_PageUnit(System::Drawing::GraphicsUnit::Millimeter);
// Reset the transformations that we used from the previous rendering.
gr->ResetTransform();
// Apply another set of transformations.
gr->TranslateTransform(10.0f, 10.0f);
gr->ScaleTransform(0.5f, 0.5f);
gr->set_PageScale(2.f);
// Create another rectangle and use it to frame another page from the document.
gr->DrawRectangle(MakeObject<System::Drawing::Pen>(System::Drawing::Color::get_Black(), 1.0f), 90, 10, 50, 100);
doc->RenderToSize(1, gr, 90.0f, 10.0f, 50.0f, 100.0f);
bmp->Save(ArtifactsDir + u"Rendering.RenderToSize.png");
}
}

◆ Save() [1/7]

Saves the document to a stream using the specified format.

Parameters
streamStream where to save the document.
saveFormatThe format in which to save the document.
Returns
Additional information that you can optionally use.
Examples

Shows how to save a document to an image via stream, and then read the image from that stream.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Name(u"Times New Roman");
builder->get_Font()->set_Size(24);
builder->Writeln(u"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
builder->InsertImage(ImageDir + u"Logo.jpg");
{
auto stream = MakeObject<System::IO::MemoryStream>();
doc->Save(stream, SaveFormat::Bmp);
stream->set_Position(0);
// Read the stream back into an image.
{
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromStream(stream);
ASPOSE_ASSERT_EQ(System::Drawing::Imaging::ImageFormat::get_Bmp(), image->get_RawFormat());
ASSERT_EQ(816, image->get_Width());
ASSERT_EQ(1056, image->get_Height());
}
}

Shows how to save a document to a stream.

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
{
auto dstStream = MakeObject<System::IO::MemoryStream>();
doc->Save(dstStream, SaveFormat::Docx);
// Verify that the stream contains the document.
ASSERT_EQ(u"Hello World!\r\rHello Word!\r\r\rHello World!", MakeObject<Document>(dstStream)->GetText().Trim());
}

◆ Save() [2/7]

Saves the document to a stream using the specified save options.

Parameters
streamStream where to save the document.
saveOptionsSpecifies 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
Additional information that you can optionally use.
Examples

Shows how to convert only some of the pages in a document to PDF.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Page 1.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page 2.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page 3.");
{
SharedPtr<System::IO::Stream> stream = System::IO::File::Create(ArtifactsDir + u"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.
auto options = MakeObject<PdfSaveOptions>();
// Set the "PageIndex" to "1" to render a portion of the document starting from the second page.
options->set_PageSet(MakeObject<PageSet>(1));
// This document will contain one page starting from page two, which will only contain the second page.
doc->Save(stream, options);
}

◆ Save() [3/7]

System::SharedPtr<Aspose::Words::Saving::SaveOutputParameters> Aspose::Words::Document::Save ( const System::String fileName)

Saves the document to a file. Automatically determines the save format from the extension.

Parameters
fileNameThe name for the document. If a document with the specified file name already exists, the existing document is overwritten.
Returns
Additional information that you can optionally use.
Examples

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

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
doc->Save(ArtifactsDir + u"Document.ConvertToPdf.pdf");

◆ Save() [4/7]

System::SharedPtr<Aspose::Words::Saving::SaveOutputParameters> Aspose::Words::Document::Save ( const System::String fileName,
Aspose::Words::SaveFormat  saveFormat 
)

Saves the document to a file in the specified format.

Parameters
fileNameThe name for the document. If a document with the specified file name already exists, the existing document is overwritten.
saveFormatThe format in which to save the document.
Returns
Additional information that you can optionally use.
Examples

Shows how to convert from DOCX to HTML format.

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
doc->Save(ArtifactsDir + u"Document.ConvertToHtml.html", SaveFormat::Html);

◆ Save() [5/7]

System::SharedPtr<Aspose::Words::Saving::SaveOutputParameters> Aspose::Words::Document::Save ( const System::String fileName,
const System::SharedPtr< Aspose::Words::Saving::SaveOptions > &  saveOptions 
)

Saves the document to a file using the specified save options.

Parameters
fileNameThe name for the document. If a document with the specified file name already exists, the existing document is overwritten.
saveOptionsSpecifies the options that control how the document is saved. Can be null.
Returns
Additional information that you can optionally use.
Examples

Shows how to improve the quality of a rendered document with SaveOptions.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Size(60);
builder->Writeln(u"Some text.");
SharedPtr<SaveOptions> options = MakeObject<Aspose::Words::Saving::ImageSaveOptions>(SaveFormat::Jpeg);
doc->Save(ArtifactsDir + u"Document.ImageSaveOptions.Default.jpg", options);
options->set_UseAntiAliasing(true);
options->set_UseHighQualityRendering(true);
doc->Save(ArtifactsDir + u"Document.ImageSaveOptions.HighQuality.jpg", options);

Shows how to render one page from a document to a JPEG image.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Page 1.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page 2.");
builder->InsertImage(ImageDir + u"Logo.jpg");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"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.
auto options = MakeObject<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->set_PageSet(MakeObject<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 + u"ImageSaveOptions.OnePage.jpg", options);

Shows how to render every page of a document to a separate TIFF image.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Page 1.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page 2.");
builder->InsertImage(ImageDir + u"Logo.jpg");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"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.
auto options = MakeObject<ImageSaveOptions>(SaveFormat::Tiff);
for (int i = 0; i < doc->get_PageCount(); i++)
{
// Set the "PageSet" property to the number of the first page from
// which to start rendering the document from.
options->set_PageSet(MakeObject<PageSet>(i));
doc->Save(ArtifactsDir + String::Format(u"ImageSaveOptions.PageByPage.{0}.tiff", i + 1), options);
}

Shows how to configure compression while saving a document as a JPEG.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertImage(ImageDir + u"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.
auto imageOptions = MakeObject<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->set_JpegQuality(10);
doc->Save(ArtifactsDir + u"ImageSaveOptions.JpegQuality.HighCompression.jpg", imageOptions);
ASSERT_GE(20000, MakeObject<System::IO::FileInfo>(ArtifactsDir + u"ImageSaveOptions.JpegQuality.HighCompression.jpg")->get_Length());
// 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->set_JpegQuality(100);
doc->Save(ArtifactsDir + u"ImageSaveOptions.JpegQuality.HighQuality.jpg", imageOptions);
ASSERT_LT(60000, MakeObject<System::IO::FileInfo>(ArtifactsDir + u"ImageSaveOptions.JpegQuality.HighQuality.jpg")->get_Length());

Shows how to convert a whole document to PDF with three levels in the document outline.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert headings of levels 1 to 5.
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
ASSERT_TRUE(builder->get_ParagraphFormat()->get_IsHeading());
builder->Writeln(u"Heading 1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 1.1");
builder->Writeln(u"Heading 1.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading3);
builder->Writeln(u"Heading 1.2.1");
builder->Writeln(u"Heading 1.2.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading4);
builder->Writeln(u"Heading 1.2.2.1");
builder->Writeln(u"Heading 1.2.2.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading5);
builder->Writeln(u"Heading 1.2.2.2.1");
builder->Writeln(u"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.
auto options = MakeObject<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->get_OutlineOptions()->set_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->get_OutlineOptions()->set_ExpandedOutlineLevels(2);
doc->Save(ArtifactsDir + u"PdfSaveOptions.ExpandedOutlineLevels.pdf", options);

◆ Save() [6/7]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Saving::SaveOutputParameters> Aspose::Words::Document::Save ( std::basic_ostream< CharType, Traits > &  stream,
Aspose::Words::SaveFormat  saveFormat 
)
inline

◆ Save() [7/7]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Saving::SaveOutputParameters> Aspose::Words::Document::Save ( std::basic_ostream< CharType, Traits > &  stream,
System::SharedPtr< Aspose::Words::Saving::SaveOptions saveOptions 
)
inline

◆ set_AttachedTemplate()

void Aspose::Words::Document::set_AttachedTemplate ( const System::String value)

◆ set_AutomaticallyUpdateStyles()

void Aspose::Words::Document::set_AutomaticallyUpdateStyles ( bool  value)

◆ set_CustomXmlParts()

void Aspose::Words::Document::set_CustomXmlParts ( const System::SharedPtr< Aspose::Words::Markup::CustomXmlPartCollection > &  value)

◆ set_DefaultTabStop()

void Aspose::Words::Document::set_DefaultTabStop ( double  value)

◆ set_FontSettings()

void Aspose::Words::Document::set_FontSettings ( const System::SharedPtr< Aspose::Words::Fonts::FontSettings > &  value)

◆ set_GlossaryDocument()

void Aspose::Words::Document::set_GlossaryDocument ( const System::SharedPtr< Aspose::Words::BuildingBlocks::GlossaryDocument > &  value)

◆ set_GrammarChecked()

void Aspose::Words::Document::set_GrammarChecked ( bool  value)

◆ set_MailMergeSettings()

void Aspose::Words::Document::set_MailMergeSettings ( const System::SharedPtr< Aspose::Words::Settings::MailMergeSettings > &  value)

◆ set_PackageCustomParts()

void Aspose::Words::Document::set_PackageCustomParts ( const System::SharedPtr< Aspose::Words::Markup::CustomPartCollection > &  value)

◆ set_RemovePersonalInformation()

void Aspose::Words::Document::set_RemovePersonalInformation ( bool  value)

◆ set_RevisionsView()

void Aspose::Words::Document::set_RevisionsView ( Aspose::Words::RevisionsView  value)

◆ set_ShadeFormData()

void Aspose::Words::Document::set_ShadeFormData ( bool  value)

◆ set_ShowGrammaticalErrors()

void Aspose::Words::Document::set_ShowGrammaticalErrors ( bool  value)

◆ set_ShowSpellingErrors()

void Aspose::Words::Document::set_ShowSpellingErrors ( bool  value)

◆ set_SpellingChecked()

void Aspose::Words::Document::set_SpellingChecked ( bool  value)

◆ set_TrackRevisions()

void Aspose::Words::Document::set_TrackRevisions ( bool  value)

◆ set_VbaProject()

void Aspose::Words::Document::set_VbaProject ( const System::SharedPtr< Aspose::Words::Vba::VbaProject > &  value)

◆ StartTrackRevisions() [1/2]

void Aspose::Words::Document::StartTrackRevisions ( const System::String author)

Starts automatically marking all further changes you make to the document programmatically as revision changes.

If you call this method and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.

Currently Aspose.Words supports tracking of node insertions and deletions only. Formatting changes are not recorded as revisions.

Automatic tracking of changes is supported both when modifying this document through node manipulations as well as when using DocumentBuilder

This method does not change the TrackRevisions option and does not use its value for the purposes of revision tracking.

Parameters
authorInitials of the author to use for revisions.
See also
Aspose::Words::Document::StopTrackRevisions
Examples

Shows how to track revisions while editing a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Editing a document usually does not count as a revision until we begin tracking them.
builder->Write(u"Hello world! ");
ASSERT_EQ(0, doc->get_Revisions()->get_Count());
ASSERT_FALSE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(0)->get_IsInsertRevision());
doc->StartTrackRevisions(u"John Doe");
builder->Write(u"Hello again! ");
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_TRUE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(1)->get_IsInsertRevision());
ASSERT_EQ(u"John Doe", doc->get_Revisions()->idx_get(0)->get_Author());
ASSERT_LE((System::DateTime::get_Now() - doc->get_Revisions()->idx_get(0)->get_DateTime()).get_Milliseconds(), 10);
// Stop tracking revisions to not count any future edits as revisions.
doc->StopTrackRevisions();
builder->Write(u"Hello again! ");
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_FALSE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(2)->get_IsInsertRevision());
// 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(u"John Doe", System::DateTime::MinValue);
builder->Write(u"Hello again! ");
ASSERT_EQ(2, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"John Doe", doc->get_Revisions()->idx_get(1)->get_Author());
ASSERT_EQ(System::DateTime::MinValue, doc->get_Revisions()->idx_get(1)->get_DateTime());
// 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 + u"Document.StartTrackRevisions.docx");

◆ StartTrackRevisions() [2/2]

void Aspose::Words::Document::StartTrackRevisions ( const System::String author,
System::DateTime  dateTime 
)

Starts automatically marking all further changes you make to the document programmatically as revision changes.

If you call this method and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.

Currently Aspose.Words supports tracking of node insertions and deletions only. Formatting changes are not recorded as revisions.

Automatic tracking of changes is supported both when modifying this document through node manipulations as well as when using DocumentBuilder

This method does not change the TrackRevisions option and does not use its value for the purposes of revision tracking.

Parameters
authorInitials of the author to use for revisions.
dateTimeThe date and time to use for revisions.
See also
Aspose::Words::Document::StopTrackRevisions
Examples

Shows how to track revisions while editing a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Editing a document usually does not count as a revision until we begin tracking them.
builder->Write(u"Hello world! ");
ASSERT_EQ(0, doc->get_Revisions()->get_Count());
ASSERT_FALSE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(0)->get_IsInsertRevision());
doc->StartTrackRevisions(u"John Doe");
builder->Write(u"Hello again! ");
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_TRUE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(1)->get_IsInsertRevision());
ASSERT_EQ(u"John Doe", doc->get_Revisions()->idx_get(0)->get_Author());
ASSERT_LE((System::DateTime::get_Now() - doc->get_Revisions()->idx_get(0)->get_DateTime()).get_Milliseconds(), 10);
// Stop tracking revisions to not count any future edits as revisions.
doc->StopTrackRevisions();
builder->Write(u"Hello again! ");
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_FALSE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(2)->get_IsInsertRevision());
// 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(u"John Doe", System::DateTime::MinValue);
builder->Write(u"Hello again! ");
ASSERT_EQ(2, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"John Doe", doc->get_Revisions()->idx_get(1)->get_Author());
ASSERT_EQ(System::DateTime::MinValue, doc->get_Revisions()->idx_get(1)->get_DateTime());
// 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 + u"Document.StartTrackRevisions.docx");

◆ StopTrackRevisions()

void Aspose::Words::Document::StopTrackRevisions ( )

Stops automatic marking of document changes as revisions.

See also
Aspose::Words::Document::StartTrackRevisions(System::String, System::DateTime)
Examples

Shows how to track revisions while editing a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Editing a document usually does not count as a revision until we begin tracking them.
builder->Write(u"Hello world! ");
ASSERT_EQ(0, doc->get_Revisions()->get_Count());
ASSERT_FALSE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(0)->get_IsInsertRevision());
doc->StartTrackRevisions(u"John Doe");
builder->Write(u"Hello again! ");
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_TRUE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(1)->get_IsInsertRevision());
ASSERT_EQ(u"John Doe", doc->get_Revisions()->idx_get(0)->get_Author());
ASSERT_LE((System::DateTime::get_Now() - doc->get_Revisions()->idx_get(0)->get_DateTime()).get_Milliseconds(), 10);
// Stop tracking revisions to not count any future edits as revisions.
doc->StopTrackRevisions();
builder->Write(u"Hello again! ");
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
ASSERT_FALSE(doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_Runs()->idx_get(2)->get_IsInsertRevision());
// 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(u"John Doe", System::DateTime::MinValue);
builder->Write(u"Hello again! ");
ASSERT_EQ(2, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"John Doe", doc->get_Revisions()->idx_get(1)->get_Author());
ASSERT_EQ(System::DateTime::MinValue, doc->get_Revisions()->idx_get(1)->get_DateTime());
// 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 + u"Document.StartTrackRevisions.docx");

◆ Type()

static const System::TypeInfo& Aspose::Words::Document::Type ( )
static

◆ UnlinkFields()

void Aspose::Words::Document::UnlinkFields ( )

Unlinks fields in the whole document.

Replaces all the fields in the whole document with their most recent results.

To unlink fields in a specific part of the document use UnlinkFields.

Examples

Shows how to unlink all fields in the document.

auto doc = MakeObject<Document>(MyDir + u"Linked fields.docx");
doc->UnlinkFields();

◆ Unprotect() [1/2]

void Aspose::Words::Document::Unprotect ( )

Removes protection from the document regardless of the password.

This method unprotects the document even if it has a protection password.

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

Examples

Shows how to protect and unprotect a document.

auto doc = MakeObject<Document>();
doc->Protect(ProtectionType::ReadOnly, u"password");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
// 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 + u"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.
auto protectedDoc = MakeObject<Document>(ArtifactsDir + u"Document.Protect.docx");
ASSERT_EQ(ProtectionType::ReadOnly, protectedDoc->get_ProtectionType());
auto builder = MakeObject<DocumentBuilder>(protectedDoc);
builder->Writeln(u"Text added to a protected document.");
// There are two ways of removing protection from a document.
// 1 - With no password:
doc->Unprotect();
ASSERT_EQ(ProtectionType::NoProtection, doc->get_ProtectionType());
doc->Protect(ProtectionType::ReadOnly, u"NewPassword");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
doc->Unprotect(u"WrongPassword");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
// 2 - With the correct password:
doc->Unprotect(u"NewPassword");
ASSERT_EQ(ProtectionType::NoProtection, doc->get_ProtectionType());

◆ Unprotect() [2/2]

bool Aspose::Words::Document::Unprotect ( const System::String password)

Removes protection from the document if a correct password is specified.

This method unprotects the document only if a correct password is specified.

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

Parameters
passwordThe password to unprotect the document with.
Returns
True if a correct password was specified and the document was unprotected.
Examples

Shows how to protect and unprotect a document.

auto doc = MakeObject<Document>();
doc->Protect(ProtectionType::ReadOnly, u"password");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
// 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 + u"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.
auto protectedDoc = MakeObject<Document>(ArtifactsDir + u"Document.Protect.docx");
ASSERT_EQ(ProtectionType::ReadOnly, protectedDoc->get_ProtectionType());
auto builder = MakeObject<DocumentBuilder>(protectedDoc);
builder->Writeln(u"Text added to a protected document.");
// There are two ways of removing protection from a document.
// 1 - With no password:
doc->Unprotect();
ASSERT_EQ(ProtectionType::NoProtection, doc->get_ProtectionType());
doc->Protect(ProtectionType::ReadOnly, u"NewPassword");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
doc->Unprotect(u"WrongPassword");
ASSERT_EQ(ProtectionType::ReadOnly, doc->get_ProtectionType());
// 2 - With the correct password:
doc->Unprotect(u"NewPassword");
ASSERT_EQ(ProtectionType::NoProtection, doc->get_ProtectionType());

◆ UpdateFields()

void Aspose::Words::Document::UpdateFields ( )

Updates the values of fields in the whole document.

When you open, modify and then save a document, Aspose.Words does not update fields automatically, it keeps them intact. Therefore, you would usually want to call this method before saving if you have modified the document programmatically and want to make sure the proper (calculated) field values appear in the saved document.

There is no need to update fields after executing a mail merge because mail merge is a kind of field update and automatically updates all fields in the document.

This method does not update all field types. For the detailed list of supported field types, see the Programmers Guide.

This method does not update fields that are related to the page layout algorithms (e.g. PAGE, PAGES, PAGEREF). The page layout-related fields are updated when you render a document or call UpdatePageLayout.

Use the NormalizeFieldTypes method before fields updating if there were document changes that affected field types.

To update fields in a specific part of the document use UpdateFields.

Examples

Shows how to insert a Table of contents (TOC) into a document using heading styles as entries.

auto doc = MakeObject<Document>();
auto builder = MakeObject<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(u"\\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->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 1.1");
builder->Writeln(u"Heading 1.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 2");
builder->Writeln(u"Heading 3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading3);
builder->Writeln(u"Heading 3.1.1");
builder->Writeln(u"Heading 3.1.2");
builder->Writeln(u"Heading 3.1.3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading4);
builder->Writeln(u"Heading 3.1.3.1");
builder->Writeln(u"Heading 3.1.3.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.2");
builder->Writeln(u"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 + u"DocumentBuilder.InsertToc.docx");

Shows to use the QUOTE field.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a QUOTE field, which will display the value of its Text property.
auto field = System::DynamicCast<FieldQuote>(builder->InsertField(FieldType::FieldQuote, true));
field->set_Text(u"\"Quoted text\"");
ASSERT_EQ(u" QUOTE \"\\\"Quoted text\\\"\"", field->GetFieldCode());
// 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(u"\nDocument creation date: ");
field = System::DynamicCast<FieldQuote>(builder->InsertField(FieldType::FieldQuote, true));
builder->MoveTo(field->get_Separator());
builder->InsertField(FieldType::FieldDate, true);
ASSERT_EQ(String(u" QUOTE \u0013 DATE \u0014") + System::DateTime::get_Now().get_Date().ToShortDateString() + u"\u0015", field->GetFieldCode());
// Update all the fields to display their correct results.
doc->UpdateFields();
ASSERT_EQ(u"\"Quoted text\"", doc->get_Range()->get_Fields()->idx_get(0)->get_Result());
doc->Save(ArtifactsDir + u"Field.QUOTE.docx");

Shows how to set user details, and display them using fields.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a UserInformation object and set it as the data source for fields that display user information.
auto userInformation = MakeObject<UserInformation>();
userInformation->set_Name(u"John Doe");
userInformation->set_Initials(u"J. D.");
userInformation->set_Address(u"123 Main Street");
doc->get_FieldOptions()->set_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_EQ(userInformation->get_Name(), builder->InsertField(u" USERNAME ")->get_Result());
ASSERT_EQ(userInformation->get_Initials(), builder->InsertField(u" USERINITIALS ")->get_Result());
ASSERT_EQ(userInformation->get_Address(), builder->InsertField(u" USERADDRESS ")->get_Result());
// The field options object also has a static default user that fields from all documents can refer to.
UserInformation::get_DefaultUser()->set_Name(u"Default User");
UserInformation::get_DefaultUser()->set_Initials(u"D. U.");
UserInformation::get_DefaultUser()->set_Address(u"One Microsoft Way");
doc->get_FieldOptions()->set_CurrentUser(UserInformation::get_DefaultUser());
ASSERT_EQ(u"Default User", builder->InsertField(u" USERNAME ")->get_Result());
ASSERT_EQ(u"D. U.", builder->InsertField(u" USERINITIALS ")->get_Result());
ASSERT_EQ(u"One Microsoft Way", builder->InsertField(u" USERADDRESS ")->get_Result());
doc->UpdateFields();
doc->Save(ArtifactsDir + u"FieldOptions.CurrentUser.docx");

◆ UpdateListLabels()

void Aspose::Words::Document::UpdateListLabels ( )

Updates list labels for all list items in the document.

This method updates list label properties such as LabelValue and LabelString for each ListLabel object in the document.

Also, this method is sometimes implicitly called when updating fields in the document. This is required because some fields that may reference list numbers (such as TOC or REF) need them be up-to-date.

Examples

Shows how to extract the list labels of all paragraphs that are list items.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
doc->UpdateListLabels();
SharedPtr<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.
for (auto paragraph : System::IterateOver(
paras->LINQ_OfType<SharedPtr<Paragraph>>()->LINQ_Where([](SharedPtr<Paragraph> p) { return p->get_ListFormat()->get_IsListItem(); })))
{
std::cout << "List item paragraph #" << paras->IndexOf(paragraph) << std::endl;
// 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();
std::cout << "\tExported Text: " << paragraphText << std::endl;
SharedPtr<ListLabel> label = paragraph->get_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.
std::cout << "\tNumerical Id: " << label->get_LabelValue() << std::endl;
// Combine them together to include the list label with the text in the output.
std::cout << "\tList label combined with text: " << label->get_LabelString() << " " << paragraphText << std::endl;
}

◆ UpdatePageLayout()

void Aspose::Words::Document::UpdatePageLayout ( )

Rebuilds the page layout of the document.

This method formats a document into pages and updates the page number related fields in the document such as PAGE, PAGES, PAGEREF and REF. The up-to-date page layout information is required for a correct rendering of the document to fixed-page formats.

This method is automatically invoked when you first convert a document to PDF, XPS, image or print it. However, if you modify the document after rendering and then attempt to render it again - Aspose.Words will not update the page layout automatically. In this case you should call UpdatePageLayout before rendering again.

Examples

Shows when to recalculate the page layout of the document.

auto doc = MakeObject<Document>(MyDir + u"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 + u"Document.UpdatePageLayout.1.pdf");
// Modify the document in some way.
doc->get_Styles()->idx_get(u"Normal")->get_Font()->set_Size(6);
doc->get_Sections()->idx_get(0)->get_PageSetup()->set_Orientation(Orientation::Landscape);
// 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 + u"Document.UpdatePageLayout.2.pdf");

◆ UpdateTableLayout()

void Aspose::Words::Document::UpdateTableLayout ( )

Updates widths of cells and tables in the document according to their preferred widths and content. You do not need to call this method if the tables appear correct in the output document.

You do not normally need to call this method as cell and table widths are maintained automatically. You can call this method before exporting to PDF (or any other fixed-page format), only in rare cases where you confirmed that tables appear incorrectly laid out in the output document. Calling this method might help to correct the output.

Examples

Shows how to preserve a table's layout when saving to .txt.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Cell 1");
builder->InsertCell();
builder->Write(u"Cell 2");
builder->InsertCell();
builder->Write(u"Cell 3");
builder->EndTable();
// Use a TxtSaveOptions object to preserve the table's layout when converting the document to plaintext.
auto options = MakeObject<TxtSaveOptions>();
options->set_PreserveTableLayout(true);
// Previewing the appearance of the document in .txt form shows that the table will not be represented accurately.
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_Width());
ASSERT_EQ(u"CCC\r\neee\r\nlll\r\nlll\r\n \r\n123\r\n\r\n", doc->ToString(options));
// We can call UpdateTableLayout() to fix some of these issues.
doc->UpdateTableLayout();
ASSERT_EQ(u"Cell 1 Cell 2 Cell 3\r\n\r\n", doc->ToString(options));
ASSERT_NEAR(155.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_Width(), 2.f);

◆ UpdateThumbnail() [1/2]

void Aspose::Words::Document::UpdateThumbnail ( )

Updates Thumbnail of the document using default options.

Examples

Shows how to update a document's thumbnail.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world!");
builder->InsertImage(ImageDir + u"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 + u"Document.UpdateThumbnail.FirstPage.epub");
// 2 - Use the first image found in the document:
auto options = MakeObject<ThumbnailGeneratingOptions>();
options->set_ThumbnailSize(System::Drawing::Size(400, 400));
options->set_GenerateFromFirstPage(false);
doc->UpdateThumbnail(options);
doc->Save(ArtifactsDir + u"Document.UpdateThumbnail.FirstImage.epub");

◆ UpdateThumbnail() [2/2]

void Aspose::Words::Document::UpdateThumbnail ( const System::SharedPtr< Aspose::Words::Rendering::ThumbnailGeneratingOptions > &  options)

Updates Thumbnail of the document according to the specified options.

Parameters
optionsThe generating options to use.
Examples

Shows how to update a document's thumbnail.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world!");
builder->InsertImage(ImageDir + u"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 + u"Document.UpdateThumbnail.FirstPage.epub");
// 2 - Use the first image found in the document:
auto options = MakeObject<ThumbnailGeneratingOptions>();
options->set_ThumbnailSize(System::Drawing::Size(400, 400));
options->set_GenerateFromFirstPage(false);
doc->UpdateThumbnail(options);
doc->Save(ArtifactsDir + u"Document.UpdateThumbnail.FirstImage.epub");

◆ UpdateWordCount() [1/2]

void Aspose::Words::Document::UpdateWordCount ( )

Updates word count properties of the document.

UpdateWordCount recalculates and updates Characters, Words and Paragraphs properties in the BuiltInDocumentProperties collection of the Document.

Note that UpdateWordCount does not update number of lines and pages properties. Use the UpdateWordCount overload and pass True value as a parameter to do that.

When you use an evaluation version, the evaluation watermark will also be included in the word count.

Examples

Shows how to update all list labels in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(String(u"Lorem ipsum dolor sit amet, consectetur adipiscing elit, ") +
u"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
builder->Write(String(u"Ut enim ad minim veniam, ") + u"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_EQ(0, doc->get_BuiltInDocumentProperties()->get_Characters());
ASSERT_EQ(0, doc->get_BuiltInDocumentProperties()->get_Words());
ASSERT_EQ(1, doc->get_BuiltInDocumentProperties()->get_Paragraphs());
ASSERT_EQ(1, doc->get_BuiltInDocumentProperties()->get_Lines());
// To get accurate values for three of these properties, we will need to update them manually.
doc->UpdateWordCount();
ASSERT_EQ(196, doc->get_BuiltInDocumentProperties()->get_Characters());
ASSERT_EQ(36, doc->get_BuiltInDocumentProperties()->get_Words());
ASSERT_EQ(2, doc->get_BuiltInDocumentProperties()->get_Paragraphs());
// For the line count, we will need to call a specific overload of the updating method.
ASSERT_EQ(1, doc->get_BuiltInDocumentProperties()->get_Lines());
doc->UpdateWordCount(true);
ASSERT_EQ(4, doc->get_BuiltInDocumentProperties()->get_Lines());

◆ UpdateWordCount() [2/2]

void Aspose::Words::Document::UpdateWordCount ( bool  updateLinesCount)

Updates word count properties of the document, optionally updates Lines property.

Parameters
updateLinesCountTrue if number of lines in the document shall be calculated.
Examples

Shows how to update all list labels in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(String(u"Lorem ipsum dolor sit amet, consectetur adipiscing elit, ") +
u"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
builder->Write(String(u"Ut enim ad minim veniam, ") + u"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_EQ(0, doc->get_BuiltInDocumentProperties()->get_Characters());
ASSERT_EQ(0, doc->get_BuiltInDocumentProperties()->get_Words());
ASSERT_EQ(1, doc->get_BuiltInDocumentProperties()->get_Paragraphs());
ASSERT_EQ(1, doc->get_BuiltInDocumentProperties()->get_Lines());
// To get accurate values for three of these properties, we will need to update them manually.
doc->UpdateWordCount();
ASSERT_EQ(196, doc->get_BuiltInDocumentProperties()->get_Characters());
ASSERT_EQ(36, doc->get_BuiltInDocumentProperties()->get_Words());
ASSERT_EQ(2, doc->get_BuiltInDocumentProperties()->get_Paragraphs());
// For the line count, we will need to call a specific overload of the updating method.
ASSERT_EQ(1, doc->get_BuiltInDocumentProperties()->get_Lines());
doc->UpdateWordCount(true);
ASSERT_EQ(4, doc->get_BuiltInDocumentProperties()->get_Lines());