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 DataSet, DataTable, DataView, IDataReader or an array of values. MailMerge will go through the records found in the data source and insert them into mail merge fields in the document growing it as necessary.

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

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

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/Model/Document/Document.h>

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

Public Member Functions

 Document ()
 Creates a blank Word document. More...
 
 Document (SharedPtr< Stream > stream)
 Opens an existing document from a stream. Automatically detects the file format. More...
 
 Document (SharedPtr< Stream > stream, SharedPtr< LoadOptions > loadOptions)
 Opens an existing document from a stream. Allows to specify additional options such as an encryption password. More...
 
 Document (String fileName)
 Opens an existing document from a file. Automatically detects the file format. More...
 
 Document (String fileName, SharedPtr< LoadOptions > loadOptions)
 Opens an existing document from a file. Allows to specify additional options such as an encryption password. More...
 
bool Accept (SharedPtr< DocumentVisitor > visitor) override
 Accepts a visitor. More...
 
void AcceptAllRevisions ()
 Accepts all tracked changes in the document. More...
 
void Add (SharedPtr< Shape > watermark) override
 
void AppendDocument (SharedPtr< Document > srcDoc, ImportFormatMode importFormatMode)
 Appends the specified document to the end of this document. More...
 
void AppendDocument (SharedPtr< Document > srcDoc, ImportFormatMode importFormatMode, 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 (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 (SharedPtr< Document > document, String author, DateTime dateTime)
 Compares this document with another document producing changes as number of edit and format revisions Revision. More...
 
void Compare (SharedPtr< Document > document, String author, DateTime dateTime, 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 (SharedPtr< Document > template_)
 Copies styles from the specified template to a document. More...
 
void CopyStylesFromTemplate (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...
 
SharedPtr< ShapeGet () override
 
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< 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, String password)
 Protects the document from changes and optionally sets a protection password. More...
 
void Remove () override
 Removes itself from the parent. 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, SharedPtr< Graphics > graphics, float x, float y, float scale)
 Renders a document page into a Graphics object to a specified scale. More...
 
float RenderToSize (int32_t pageIndex, SharedPtr< Graphics > graphics, float x, float y, float width, float height)
 Renders a document page into a Graphics object to a specified size. More...
 
SharedPtr< SaveOutputParametersSave (SharedPtr< Stream > stream, SaveFormat saveFormat)
 Saves the document to a stream using the specified format. More...
 
SharedPtr< SaveOutputParametersSave (SharedPtr< Stream > stream, SharedPtr< SaveOptions > saveOptions)
 Saves the document to a stream using the specified save options. More...
 
SharedPtr< SaveOutputParametersSave (String fileName)
 Saves the document to a file. Automatically determines the save format from the extension. More...
 
SharedPtr< SaveOutputParametersSave (String fileName, SaveFormat saveFormat)
 Saves the document to a file in the specified format. More...
 
SharedPtr< SaveOutputParametersSave (String fileName, SharedPtr< SaveOptions > saveOptions)
 Saves the document to a file using the specified save options. More...
 
void set_AttachedTemplate (String value)
 Setter for get_AttachedTemplate. More...
 
void set_AutomaticallyUpdateStyles (bool value)
 Setter for get_AutomaticallyUpdateStyles. More...
 
void set_CustomXmlParts (SharedPtr< CustomXmlPartCollection > value)
 Setter for get_CustomXmlParts. More...
 
void set_DefaultTabStop (double value)
 Setter for get_DefaultTabStop. More...
 
void set_FontSettings (SharedPtr< FontSettings > value)
 Setter for get_FontSettings. More...
 
void set_GlossaryDocument (SharedPtr< GlossaryDocument > value)
 Setter for get_GlossaryDocument. More...
 
void set_GrammarChecked (bool value)
 Returns true if the document has been checked for grammar. More...
 
void set_MailMergeSettings (SharedPtr< MailMergeSettings > value)
 Setter for get_MailMergeSettings. More...
 
void set_PackageCustomParts (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)
 Returns true if the document has been checked for spelling. More...
 
void set_TrackRevisions (bool value)
 Setter for get_TrackRevisions. More...
 
void set_VbaProject (SharedPtr< VbaProject > value)
 Setter for get_VbaProject. More...
 
void StartTrackRevisions (String author)
 Starts automatically marking all further changes you make to the document programmatically as revision changes. More...
 
void StartTrackRevisions (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 (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 (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 (SharedPtr< Node > srcNode, bool isImportChildren)
 Imports a node from another document to the current document. More...
 
SharedPtr< NodeImportNode (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 (SharedPtr< Shape > value)
 Setter for get_BackgroundShape. More...
 
void set_NodeChangingCallback (SharedPtr< INodeChangingCallback > value)
 Setter for get_NodeChangingCallback. More...
 
void set_PageColor (Color value)
 Setter for get_PageColor. More...
 
void set_ResourceLoadingCallback (SharedPtr< IResourceLoadingCallback > value)
 Setter for get_ResourceLoadingCallback. More...
 
void set_WarningCallback (SharedPtr< IWarningCallback > value)
 Setter for get_WarningCallback. More...
 
- Public Member Functions inherited from CompositeNode
SharedPtr< NodeAppendChild (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...
 
SharedPtr< CompositeNodeget_Container () override
 
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< NodeGetCurrentNode () override
 
SharedPtr< IEnumerator< SharedPtr< Node > > > GetEnumerator () override
 Provides support for the for each style iteration over the child nodes of this node. More...
 
SharedPtr< NodeGetNextMatchingNode (SharedPtr< Node > curNode) override
 
String GetText () override
 Gets the text of this node and of all its children. More...
 
int32_t IndexOf (SharedPtr< Node > child)
 Returns the index of the specified child node in the child node array. More...
 
SharedPtr< NodeInsertAfter (SharedPtr< Node > newChild, SharedPtr< Node > refChild)
 Inserts the specified node immediately after the specified reference node. More...
 
SharedPtr< NodeInsertBefore (SharedPtr< Node > newChild, SharedPtr< Node > refChild)
 Inserts the specified node immediately before the specified reference node. More...
 
SharedPtr< NodePrependChild (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 (SharedPtr< Node > oldChild)
 Removes the specified child node. More...
 
void RemoveSmartTags ()
 Removes all SmartTag descendant nodes of the current node. More...
 
SharedPtr< NodeListSelectNodes (String xpath)
 Selects a list of nodes matching the XPath expression. More...
 
SharedPtr< NodeSelectSingleNode (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 (SharedPtr< Node > rootNode)
 Gets next node according to the pre-order tree traversal algorithm. More...
 
SharedPtr< NodePreviousPreOrder (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 (SharedPtr< SaveOptions > saveOptions)
 Exports the content of the node into a string using the specified save options. More...
 
- Public Member Functions inherited from Object
 Object ()
 
 Object (Object const &x)
 
virtual ~Object ()
 
virtual bool Equals (ptr obj)
 
virtual bool FastCast (const Details::FastRttiBase &helper, void **out_ptr) const
 
Detail::SmartPtrCounter * GetCounter ()
 
virtual int32_t GetHashCode () const
 
void Lock ()
 
virtual ptr MemberwiseClone () const
 
Objectoperator= (Object const &x)
 
bool ReferenceEquals (String const &str, std::nullptr_t)
 
bool ReferenceEquals (String const &str1, String const &str2)
 
int RemovedSharedRefs (int count)
 
virtual void SetTemplateWeakPtr (unsigned int argument)
 
int SharedCount () const
 
ObjectSharedRefAdded ()
 
int SharedRefRemovedSafe ()
 
virtual String ToString () const
 
void Unlock ()
 
Detail::SmartPtrCounter * WeakRefAdded ()
 
void WeakRefRemoved ()
 
- Public Member Functions inherited from System::Collections::Generic::IEnumerable< System::SharedPtr< Aspose::Words::Node > >
const_iterator begin () const noexcept
 
iterator begin () noexcept
 
const_iterator cbegin () const noexcept
 
const_iterator cend () const noexcept
 
const_iterator end () const noexcept
 
iterator end () noexcept
 
bool LINQ_All (std::function< bool(T)> predicate)
 
bool LINQ_Any ()
 
bool LINQ_Any (std::function< bool(T)> predicate)
 
SharedPtr< IEnumerable< ResultType > > LINQ_Cast ()
 
SharedPtr< IEnumerable< Result > > LINQ_Cast ()
 
SharedPtr< IEnumerable< T > > LINQ_Concat (SharedPtr< IEnumerable< T >> sequence)
 
bool LINQ_Contains (T value)
 
int LINQ_Count ()
 
int LINQ_Count (const Func< T, bool > &predicate)
 
LINQ_ElementAt (int index)
 
LINQ_First ()
 
LINQ_First (const Func< T, bool > &predicate)
 
LINQ_FirstOrDefault ()
 
LINQ_FirstOrDefault (std::function< bool(T)> predicate)
 
LINQ_Last ()
 
LINQ_LastOrDefault ()
 
SharedPtr< IEnumerable< ResultType > > LINQ_OfType ()
 
SharedPtr< IEnumerable< Result > > LINQ_OfType ()
 
SharedPtr< IEnumerable< Source > > LINQ_OrderBy (const Func< Source, Key > &keySelector)
 
SharedPtr< IEnumerable< T > > LINQ_OrderBy (const Func< T, Key > &keySelector)
 
SharedPtr< IEnumerable< Result > > LINQ_Select (const Func< Source, Result > &selector)
 
SharedPtr< IEnumerable< ResultType > > LINQ_Select (const Func< T, ResultType > &selector)
 
ArrayPtr< T > LINQ_ToArray ()
 
SharedPtr< List< T > > LINQ_ToList ()
 
SharedPtr< IEnumerable< T > > LINQ_Where (std::function< bool(T)> predicate)
 

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 ()
 
- Static Public Member Functions inherited from Object
bool Equals (double const &objA, double const &objB)
 
bool Equals (float const &objA, float const &objB)
 
static std::enable_if<!IsSmartPtr< T1 >::value &&!IsSmartPtr< T2 >::value, bool >::type Equals (T1 const &objA, T2 const &objB)
 
static std::enable_if< IsSmartPtr< T1 >::value &&IsSmartPtr< T2 >::value, bool >::type Equals (T1 const &objA, T2 const &objB)
 
static bool ReferenceEquals (ptr const &objA, ptr const &objB)
 
static std::enable_if<!IsSmartPtr< T >::value, bool >::type ReferenceEquals (T const &objA, std::nullptr_t)
 
static std::enable_if<!IsSmartPtr< T >::value, bool >::type ReferenceEquals (T const &objA, T const &objB)
 
static const TypeInfoType ()
 

Additional Inherited Members

- Public Types inherited from Object
typedef SmartPtr< Objectptr
 
typedef System::Details::SharedMembersType shared_members_type
 
- Public Types inherited from System::Collections::Generic::IEnumerable< System::SharedPtr< Aspose::Words::Node > >
typedef iterator const_iterator
 
typedef IEnumerator< T > IEnumeratorType
 
typedef EnumeratorBasedIterator< T, IEnumerator< T > > iterator
 
typedef T ValueType
 
- Protected Member Functions inherited from System::Collections::Generic::IEnumerable< System::SharedPtr< Aspose::Words::Node > >
 ~IEnumerable () override
 

Constructor & Destructor Documentation

◆ Document() [1/5]

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 a section, body, and paragraph;
// the minimal set of nodes required to begin editing.
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 add a formatted run of text to a document using the object model.

auto doc = MakeObject<Document>();
// Create a new run of text
auto run = MakeObject<Run>(doc, u"Hello");
// Specify character formatting for the run of text
SharedPtr<Aspose::Words::Font> f = run->get_Font();
f->set_Name(u"Courier New");
f->set_Size(36);
f->set_HighlightColor(System::Drawing::Color::get_Yellow());
// Append the run of text to the end of the first paragraph
// in the body of the first section of the document
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(run);
static Color get_Yellow()

◆ Document() [2/5]

Aspose::Words::Document::Document ( 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/5]

Aspose::Words::Document::Document ( System::String  fileName,
System::SharedPtr< Aspose::Words::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 a section, body, and paragraph;
// the minimal set of nodes required to begin editing.
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(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);
}
static FileStreamPtr OpenRead(const String &path)
System::ExceptionWrapper< Details_IncorrectPasswordException > IncorrectPasswordException
Thrown if a document is encrypted with a password and the password specified when opening the documen...
Definition: IncorrectPasswordException.h:33

◆ Document() [4/5]

Aspose::Words::Document::Document ( 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/5]

Aspose::Words::Document::Document ( System::SharedPtr< System::IO::Stream stream,
System::SharedPtr< Aspose::Words::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);
}
static double PointToPixel(double points)
Converts points to pixels at 96 dpi.
@ Shape
A drawing object, such as an OfficeArt shape, image or an OLE object. A Shape node can contain Paragr...

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.
ASSERT_EQ(u"File Format APIs", doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(1)->get_Runs()->idx_get(0)->GetText().Trim());
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(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);
}

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 of 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>();
}
{
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);
}
};
String ToString() const
System::String GetText() override
Gets the text of this node and of all its children.
@ Section
A Section object that corresponds to one section in a Word document. A Section node can have Body and...
@ Any
Indicates all node types. Allows to select all children.
VisitorAction
Allows the visitor to control the enumeration of nodes.
Definition: VisitorAction.h:22
@ Continue
The visitor requests the enumeration to continue.

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

◆ Add()

void Aspose::Words::Document::Add ( System::SharedPtr< Aspose::Words::Drawing::Shape watermark)
override

◆ AppendDocument() [1/2]

void Aspose::Words::Document::AppendDocument ( 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");
@ KeepSourceFormatting
Copy all required styles to the destination document, generate unique style names if needed.

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 (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");
static ArrayPtr< String > GetFiles(const String &path, const String &searchPattern=u"*", SearchOption searchOption=SearchOption::TopDirectoryOnly)
static System::SharedPtr< Aspose::Words::FileFormatInfo > DetectFileFormat(System::String fileName)
Detects and returns the information about a format of a document stored in a disk file.
@ UseDestinationStyles
Use the destination document styles and copy new styles. This is the default option.
@ Heading1
The Heading 1 style.

◆ AppendDocument() [2/2]

void Aspose::Words::Document::AppendDocument ( System::SharedPtr< Aspose::Words::Document srcDoc,
Aspose::Words::ImportFormatMode  importFormatMode,
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.

// Open 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.
auto options = MakeObject<ImportFormatOptions>();
options->set_KeepSourceNumbering(true);
// 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");
static Color get_DarkRed()
@ KeepDifferentStyles
Only copy styles that are different from those in the source document.

◆ 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());
@ List
The style is a list style.
@ Character
The style is a character style.

◆ Cleanup() [2/2]

void Aspose::Words::Document::Cleanup ( 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);
doc->Cleanup(cleanupOptions);
ASSERT_EQ(6, 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(4, 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)));
static int GetHashCode(const T &obj)

◆ Compare() [1/2]

void Aspose::Words::Document::Compare ( System::SharedPtr< Aspose::Words::Document document,
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's different in the edited document.
for (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());
std::enable_if_t<!Details::IsIterable< Enumerable >::value, Details::EnumeratorAdapter< Enumerable, T > > IterateOver(System::SmartPtr< Enumerable > enumerable)
static DateTime get_Now()

◆ Compare() [2/2]

void Aspose::Words::Document::Compare ( System::SharedPtr< Aspose::Words::Document document,
System::String  author,
System::DateTime  dateTime,
System::SharedPtr< Aspose::Words::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>(System::StaticCast<Node>(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<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");
System::SharedPtr< Aspose::Words::Document > Clone()
Performs a deep copy of the Document.
@ HeaderPrimary
Primary header, also used for odd numbered pages.
@ Comment
A comment in a Word document. A Comment node can have Paragraph and Table nodes.
@ Table
A Table object that represents a table in a Word document. A Table node can have Row nodes.
@ Footnote
A footnote or endnote in a Word document. A Footnote node can have Paragraph and Table nodes.
@ New
Other document is used as a base during comparison.
@ Endnote
The object is an endnote.

◆ CopyStylesFromTemplate() [1/2]

void Aspose::Words::Document::CopyStylesFromTemplate ( 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());
static Color get_DeepSkyBlue()
static Color get_RoyalBlue()
static Color get_Orange()
static Color get_Navy()
@ Paragraph
The style is a paragraph style.

◆ CopyStylesFromTemplate() [2/2]

void Aspose::Words::Document::CopyStylesFromTemplate ( 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 the document 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!"));
@ Body
A Body object that contains the main text of a section (main text story). A Body node can have Paragr...
@ Paragraph
A paragraph of text. A Paragraph node is a container for inline level elements Run,...

◆ 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 attributes 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 attributes such as the ones we set above.
doc->ExpandTableStylesToDirectFormatting();
doc->Save(ArtifactsDir + u"Document.TableStyleToDirectFormatting.docx");
static Color get_AntiqueWhite()
static Color get_Blue()
@ Table
The style is a table style.

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

◆ Get()

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::Document::Get ( )
override

◆ 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");
// Some information about the document is stored in member attributes, and can be accessed like this
std::cout << "Document filename:\n\t \"" << doc->get_OriginalFileName() << "\"" << std::endl;
// Most of the document's metadata, such as author name, file size,
// word/page counts can be found in the built-in properties collection like this
std::cout << "Built-in Properties:" << std::endl;
for (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 (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;
}
}
static std::enable_if< std::is_convertible< T, Object >::value &&std::is_final< T >::value &&!System::IsBoxable< T >::value &&System::IsSmartPtr< U >::value, bool >::type Is(const U &obj)
std::enable_if< IsExceptionWrapper< TFrom >::value &&IsExceptionWrapper< TTo >::value &&(std::is_convertible< TTo, TFrom >::value||std::is_base_of< TTo, TFrom >::value), TTo >::type DynamicCast_noexcept(const TFrom &obj) noexcept

◆ 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");
// Some information about the document is stored in member attributes, and can be accessed like this
std::cout << "Document filename:\n\t \"" << doc->get_OriginalFileName() << "\"" << std::endl;
// Most of the document's metadata, such as author name, file size,
// word/page counts can be found in the built-in properties collection like this
std::cout << "Built-in Properties:" << std::endl;
for (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 (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 structured document tag with a custom XML data.

auto doc = MakeObject<Document>();
// Construct an XML part that contains data and add it to the document's collection
// Once the "Developer" tab in Microsoft Word is enabled,
// we can find elements from this collection as well as a couple defaults in the "XML Mapping Pane"
String xmlPartContent = u"<root><text>Hello world!</text></root>";
SharedPtr<CustomXmlPart> xmlPart = doc->get_CustomXmlParts()->Add(xmlPartId, xmlPartContent);
// The data we entered is stored in these attributes
ASPOSE_ASSERT_EQ(System::Text::Encoding::get_ASCII()->GetBytes(xmlPartContent), xmlPart->get_Data());
ASSERT_EQ(xmlPartId, xmlPart->get_Id());
// XML parts can be referenced by collection index or GUID
ASPOSE_ASSERT_EQ(xmlPart, doc->get_CustomXmlParts()->idx_get(0));
ASPOSE_ASSERT_EQ(xmlPart, doc->get_CustomXmlParts()->GetById(xmlPartId));
// Once the part is created, we can add XML schema associations like this
xmlPart->get_Schemas()->Add(u"http://www.w3.org/2001/XMLSchema");
// We can also clone parts and insert them into the collection directly
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 collection with an enumerator 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++;
}
}
// XML parts can be removed by index
doc->get_CustomXmlParts()->RemoveAt(1);
ASSERT_EQ(1, doc->get_CustomXmlParts()->get_Count());
// The XML part collection itself can be cloned also
SharedPtr<CustomXmlPartCollection> customXmlParts = doc->get_CustomXmlParts()->Clone();
// And all elements can be cleared like this
customXmlParts->Clear();
// Create a StructuredDocumentTag that will display the contents of our part,
// insert it into the document and save the document
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");
static Guid NewGuid()
virtual String ToString() const
static EncodingPtr get_UTF8()
static EncodingPtr get_ASCII()
String ToString() const

◆ 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!");
static constexpr char16_t TabChar
Tab character: (char)9 or "\t".
Definition: ControlChar.h:1011
static System::String & Tab()
Tab character: "\x0009" or "\t".

◆ get_DigitalSignatures()

System::SharedPtr<Aspose::Words::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 (auto signature : System::IterateOver(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());
static System::SharedPtr< Aspose::Words::CertificateHolder > Create(System::ArrayPtr< uint8_t > certBytes, System::SharedPtr< System::Security::SecureString > password)
Creates CertificateHolder object using byte array of PKCS12 store and its password.
static void Sign(System::SharedPtr< System::IO::Stream > srcStream, System::SharedPtr< System::IO::Stream > dstStream, System::SharedPtr< Aspose::Words::CertificateHolder > certHolder, System::SharedPtr< Aspose::Words::SignOptions > signOptions)
Signs source document using given CertificateHolder and SignOptions with digital signature and writes...
@ XmlDsig
The XmlDsig signature method used in OOXML and OpenDocument documents.

◆ get_EndnoteOptions()

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

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

Examples

Shows how to insert endnotes, and modify their appearance.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
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::PageBreak);
builder->Write(u"Text 3. ");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote 3", u"Custom reference mark");
doc->get_EndnoteOptions()->set_Position(EndnotePosition::EndOfDocument);
doc->get_EndnoteOptions()->set_NumberStyle(NumberStyle::UppercaseRoman);
doc->get_EndnoteOptions()->set_RestartRule(FootnoteNumberingRule::Continuous);
doc->get_EndnoteOptions()->set_StartNumber(1);
doc->Save(ArtifactsDir + u"InlineStory.Endnotes.docx");
@ UppercaseRoman
Upper case Roman (I, II, III, ...)
@ EndOfDocument
Endnotes are output at the end of the document.
@ PageBreak
Explicit page break.
@ Continuous
Numbering continuous throughout the document.

◆ 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 the document footer.

// Open the template document, containing obsolete copyright information in the 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");
int get_Year() const
@ FooterPrimary
Primary footer, also used for odd numbered pages.

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

auto doc = MakeObject<Document>();
// A blank document contains one section by default,
// in order for us to be able to edit it straight away.
ASSERT_EQ(1, doc->get_Sections()->get_Count());
// Use a document builder to add text, and then to create a new section by inserting a section break.
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world!");
builder->InsertBreak(BreakType::SectionBreakNewPage);
ASSERT_EQ(2, doc->get_Sections()->get_Count());
// Each section is a subdivision of the document that has its own page setup settings.
// We can split up the text in the second section into two columns without affecting the first section in any way.
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");
@ SectionBreakNewPage
Specifies start of new section on a new page.
@ ColumnBreak
Explicit column break.

Shows how you can enumerate through children of a composite node and detect types of the children nodes.

// Open a document
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");
// Get the first section in the document
SharedPtr<Section> section = doc->get_FirstSection();
// A Section is a composite node and therefore can contain child nodes
// Section can contain only Body and HeaderFooter nodes
for (auto node : System::IterateOver(section))
{
// Every node has the NodeType property
switch (node->get_NodeType())
{
// If the node type is Body, we can cast the node to the Body class
auto body = System::DynamicCast<Body>(node);
// Write the content of the main story of the section to the console
std::cout << "*** Body ***" << std::endl;
std::cout << body->GetText() << std::endl;
break;
}
// If the node type is HeaderFooter, we can cast the node to the HeaderFooter class
auto headerFooter = System::DynamicCast<HeaderFooter>(node);
// Write the content of the header footer to the console
std::cout << "*** HeaderFooter ***" << std::endl;
std::cout << System::EnumGetName(headerFooter->get_HeaderFooterType()) << std::endl;
std::cout << headerFooter->GetText() << std::endl;
break;
}
default: {
// Other types of nodes never occur inside a Section node
throw System::Exception(u"Unexpected node type in a section.");
}
}
}
static System::String EnumGetName(T value)
ExceptionWrapper< Details_Exception > Exception
@ HeaderFooter
A HeaderFooter object that contains text of a particular header or footer inside 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 to define alternative fonts if original does not exist

auto fontSettings = MakeObject<FontSettings>();
fontSettings->get_SubstitutionSettings()->get_TableSubstitution()->SetSubstitutes(u"Times New Roman", MakeArray<String>({u"Slab", u"Arvo"}));

◆ get_FootnoteOptions()

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

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

◆ 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 attributes categorize building blocks
// in the menu found via Insert -> Quick Parts -> Building Blocks Organizer in Microsoft Word.
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.
// We will do that and set a category, gallery, and behavior with a document visitor.
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 attributes 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;
};
static String ToString(const char_t *obj)
static Guid Parse(const String &input)

◆ get_GrammarChecked()

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

Returns true if the document has been checked for grammar.

◆ 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 that enable us to run macros by clicking.

// Open a document that contains macros
auto doc = MakeObject<Document>(MyDir + u"Macro.docm");
auto builder = MakeObject<DocumentBuilder>(doc);
ASSERT_TRUE(doc->get_HasMacros());
// Insert a MACROBUTTON field and reference by name a macro that exists within the input document
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());
// Reference "ViewZoom200", a macro that was shipped with Microsoft Word, found under "Word commands"
// If our document has a macro of the same name as one from another source, the field will select ours to run
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);
// Standard 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 is turned on in Microsoft Word,
// and it is independent of the programmatic revision tracking that is taking place here.
ASSERT_FALSE(doc->get_TrackRevisions());
// Our first revision is an insertion-type revision since we added text with the document builder.
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 are treated as document text by the GetText() method before they are accepted
// since they are still nodes with text and are in the body.
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 revision itself from the collection.
doc->get_Revisions()->idx_get(0)->Accept();
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
// Accepting a delete revision removes all the nodes that it concerns,
// so their contents will no longer be anywhere in the document.
ASSERT_EQ(u"This is revision #1.", doc->GetText().Trim());
// The insertion-type revision is now at index 0, which we can reject to ignore and discard it.
doc->get_Revisions()->idx_get(0)->Reject();
ASSERT_EQ(0, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"", doc->GetText().Trim());
constexpr DateTime get_Date() const
@ Insertion
New content was inserted in the document.
@ Deletion
Content was removed from the document.

◆ 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,
// in order for us to be able to edit it straight away.
ASSERT_EQ(1, doc->get_Sections()->get_Count());
// Use a document builder to add text, and then to create a new section by inserting a section break.
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world!");
builder->InsertBreak(BreakType::SectionBreakNewPage);
ASSERT_EQ(2, doc->get_Sections()->get_Count());
// Each section is a subdivision of the document that has its own page setup settings.
// We can split up the text in the second section into two columns without affecting the first section in any way.
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,
// and also remove the bar that appears to the left of every revised line.
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.");
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 efficiently visit all direct and indirect children of a composite node.

void RecurseAllNodes()
{
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)
{
// Loop through immediate children of a node
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
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;
}
}
}
static System::String NodeTypeToString(Aspose::Words::NodeType nodeType)
A utility method that converts a node type enum value into a user friendly string.

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());
@ Docx
Office Open XML WordprocessingML Document (macro-free).

Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.

// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format
// These are both times where you might need extract the file format as it's not visible
// The file format of this document is actually ".doc"
SharedPtr<System::IO::FileStream> docStream = System::IO::File::OpenRead(MyDir + u"Word document with missing file extension");
SharedPtr<FileFormatInfo> info = FileFormatUtil::DetectFileFormat(docStream);
// Retrieve the LoadFormat of the document
LoadFormat loadFormat = info->get_LoadFormat();
// There are two methods of converting LoadFormat enumerations to SaveFormat enumerations
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension
String fileExtension = FileFormatUtil::LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration
saveFormat = FileFormatUtil::LoadFormatToSaveFormat(loadFormat);
// Load a document from the stream.
auto doc = MakeObject<Document>(docStream);
// Save the document with the original file name, " Out" and the document's file extension
doc->Save(ArtifactsDir + u"File.SaveToDetectedFileFormat" + FileFormatUtil::SaveFormatToExtension(saveFormat));
static System::String SaveFormatToExtension(Aspose::Words::SaveFormat saveFormat)
Converts a save format enumerated value into a file extension. The returned extension is a lower-case...
static Aspose::Words::SaveFormat LoadFormatToSaveFormat(Aspose::Words::LoadFormat loadFormat)
Converts a LoadFormat value to a SaveFormat value if possible.
static System::String LoadFormatToExtension(Aspose::Words::LoadFormat loadFormat)
Converts a load format enumerated value into a file extension. The returned extension is a lower-case...
static Aspose::Words::SaveFormat ExtensionToSaveFormat(System::String extension)
Converts a file name extension into a SaveFormat value.
SaveFormat
Indicates the format in which the document is saved.
Definition: SaveFormat.h:35
LoadFormat
Indicates the format of the document that is to be loaded.
Definition: LoadFormat.h:66

◆ 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());
@ ReadOnly
No changes are allowed to the document. Available since Microsoft Word 2003.
@ NoProtection
The document is not protected.

◆ 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);
// Standard 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 is turned on in Microsoft Word,
// and it is independent of the programmatic revision tracking that is taking place here.
ASSERT_FALSE(doc->get_TrackRevisions());
// Our first revision is an insertion-type revision since we added text with the document builder.
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 are treated as document text by the GetText() method before they are accepted
// since they are still nodes with text and are in the body.
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 revision itself from the collection.
doc->get_Revisions()->idx_get(0)->Accept();
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
// Accepting a delete revision removes all the nodes that it concerns,
// so their contents will no longer be anywhere in the document.
ASSERT_EQ(u"This is revision #1.", doc->GetText().Trim());
// The insertion-type revision is now at index 0, which we can reject to ignore and discard it.
doc->get_Revisions()->idx_get(0)->Reject();
ASSERT_EQ(0, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"", 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());
@ Final
Specifies revised version of a document.

◆ 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 the section starts, from a new page, on the same page or other.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Add text to the first section and that comes with a blank document,
// then add a new section that starts a new page and give it text as well
builder->Writeln(u"This text is in section 1.");
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->Writeln(u"This text is in section 2.");
// Section break types determine how a new section gets split from the previous section
// By inserting a "SectionBreakNewPage" type section break, we have set this section's SectionStart value to "NewPage"
ASSERT_EQ(SectionStart::NewPage, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_SectionStart());
// Insert a new column section the same way
builder->InsertBreak(BreakType::SectionBreakNewColumn);
builder->Writeln(u"This text is in section 3.");
ASSERT_EQ(SectionStart::NewColumn, doc->get_Sections()->idx_get(2)->get_PageSetup()->get_SectionStart());
// We can change the types of section breaks by assigning different values to each section's SectionStart
// Setting their values to "Continuous" will put no visible breaks between sections
// and will leave all the content of this document on one page
doc->get_Sections()->idx_get(1)->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
doc->get_Sections()->idx_get(2)->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
doc->Save(ArtifactsDir + u"PageSetup.SetSectionStart.docx");
@ NewPage
The section starts from a new page.
@ NewColumn
The section starts from a new column.
@ Continuous
The new section starts on the same page as the previous section.
@ SectionBreakNewColumn
Specifies start of new section in the new column.

Shows how to add/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");
// This shows what is in the document originally. The document has two sections
ASSERT_EQ(u"Section 1\x000c"
u"Section 2",
doc->GetText().Trim());
// Delete the first section from the document
doc->get_Sections()->RemoveAt(0);
// Duplicate the last section and append the copy 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);
// Check what the document contains after we changed it
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.

◆ 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 theme colors and fonts.

auto doc = MakeObject<Document>(MyDir + u"Theme colors.docx");
// This object gives us access to the document theme, which is a source of default fonts and colors
SharedPtr<Theme> theme = doc->get_Theme();
// These fonts will be inherited by some styles like "Heading 1" and "Subtitle"
theme->get_MajorFonts()->set_Latin(u"Courier New");
theme->get_MinorFonts()->set_Latin(u"Agency FB");
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());
// This collection of colors corresponds to the color palette from Microsoft Word which appears when changing shading or font color
SharedPtr<ThemeColors> colors = theme->get_Colors();
// We will set the color of each color palette column going from left to right like this
colors->set_Light2(System::Drawing::Color::get_Khaki());
colors->set_Accent3(System::Drawing::Color::get_Yellow());
colors->set_Accent4(System::Drawing::Color::get_Gold());
// We can also set colors for hyperlinks like this
colors->set_Hyperlink(System::Drawing::Color::get_Black());
colors->set_FollowedHyperlink(System::Drawing::Color::get_Gray());
doc->Save(ArtifactsDir + u"Themes.CustomColorsAndFonts.docx");
static Color get_DarkViolet()
static Color get_LightSalmon()
static Color get_Black()
static Color get_MidnightBlue()
static Color get_Indigo()
static Color get_PaleGreen()
static Color get_Gold()
static Color get_Gray()
static Color get_BlueViolet()
static Color get_OrangeRed()
static Color get_Khaki()

◆ 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);
// Standard 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 is turned on in Microsoft Word,
// and it is independent of the programmatic revision tracking that is taking place here.
ASSERT_FALSE(doc->get_TrackRevisions());
// Our first revision is an insertion-type revision since we added text with the document builder.
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 are treated as document text by the GetText() method before they are accepted
// since they are still nodes with text and are in the body.
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 revision itself from the collection.
doc->get_Revisions()->idx_get(0)->Accept();
ASSERT_EQ(1, doc->get_Revisions()->get_Count());
// Accepting a delete revision removes all the nodes that it concerns,
// so their contents will no longer be anywhere in the document.
ASSERT_EQ(u"This is revision #1.", doc->GetText().Trim());
// The insertion-type revision is now at index 0, which we can reject to ignore and discard it.
doc->get_Revisions()->idx_get(0)->Reject();
ASSERT_EQ(0, doc->get_Revisions()->get_Count());
ASSERT_EQ(u"", 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();
// Documents have a variable collection to which name/value pairs can be added
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());
// Variables can be referenced and have their values presented in the document by 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.");
// DOCVARIABLE fields also need to be updated in order to show an accurate up to date value
field->Update();
ASSERT_EQ(u"456 Queen St.", field->get_Result());
// The existence of variables can be looked up either by name or value like this
ASSERT_TRUE(variables->Contains(u"City"));
ASSERT_TRUE(variables->LINQ_Any([](auto v) { return v.get_Value() == u"London"; }));
// Variables are automatically sorted in alphabetical order
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;
}
}
// Variables can be removed either by name or index, or the entire collection can be cleared at once
variables->Remove(u"City");
ASSERT_FALSE(variables->Contains(u"City"));
variables->RemoveAt(1);
ASSERT_FALSE(variables->Contains(u"Home address"));
variables->Clear();
ASSERT_EQ(0, variables->get_Count());

◆ get_VbaProject()

System::SharedPtr<Aspose::Words::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 (auto module_ : System::IterateOver(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 make sure the document is displayed at 50% zoom when opened in Microsoft Word.

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
// We can set the zoom factor to a percentage
doc->get_ViewOptions()->set_ViewType(ViewType::PageLayout);
doc->get_ViewOptions()->set_ZoomPercent(50);
// Or we can set the ZoomType to a different value to avoid using percentages
ASSERT_EQ(ZoomType::None, doc->get_ViewOptions()->get_ZoomType());
doc->Save(ArtifactsDir + u"ViewOptions.SetZoom.docx");

◆ 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());
@ Run
A run of text.

◆ 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 attributes 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 attributes 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 protect a section so only editing in form fields is possible.

auto doc = MakeObject<Document>();
// Insert two sections with some text
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Section 1. Unprotected.");
builder->InsertBreak(BreakType::SectionBreakContinuous);
builder->Writeln(u"Section 2. Protected.");
// Section protection only works when document protection is turned and only editing in form fields is allowed
// By default, all sections are protected, but we can selectively turn protection off
doc->get_Sections()->idx_get(0)->set_ProtectedForForms(false);
doc->Save(ArtifactsDir + u"Section.Protect.docx");
@ AllowOnlyFormFields
User can only enter data in the form fields in the document.
@ SectionBreakContinuous
Specifies start of new section on the same page as the previous section.

◆ Protect() [2/2]

void Aspose::Words::Document::Protect ( Aspose::Words::ProtectionType  type,
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());

◆ Remove()

void Aspose::Words::Document::Remove ( )
override

Removes itself from the parent.

◆ 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 of 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,
System::SharedPtr< System::Drawing::Graphics graphics,
float  x,
float  y,
float  scale 
)

Renders a document page into a Graphics 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

Renders individual pages to graphics to create one image with thumbnails of all pages.

// The user opens or builds a document
auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
// This defines the number of columns to display the thumbnails in
const int thumbColumns = 2;
// Calculate the required number of rows for thumbnails
// We can now get the number of pages in the document
int remainder;
int thumbRows = System::Math::DivRem(doc->get_PageCount(), thumbColumns, remainder);
if (remainder > 0)
{
thumbRows++;
}
// Define a zoom factor for the thumbnails
const float scale = 0.25f;
// We can use the size of the first page to calculate the size of the thumbnail,
// assuming that all pages in the document are of the same size
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);
// The Graphics object, which we will draw on, can be created from a bitmap, metafile, printer, or window
{
SharedPtr<System::Drawing::Graphics> gr = System::Drawing::Graphics::FromImage(img);
// Fill the "paper" with white, otherwise it will be transparent
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());
System::Drawing::SizeF size = doc->RenderToScale(pageIndex, gr, thumbLeft, thumbTop, scale);
// Draw the page rectangle
gr->DrawRectangle(System::Drawing::Pens::get_Black(), thumbLeft, thumbTop, size.get_Width(), size.get_Height());
}
img->Save(ArtifactsDir + u"Rendering.Thumbnails.png");
}
}
static Color get_White()
static SharedPtr< Pen > get_Black()
float get_Height() const
float get_Width() const
int get_Height() const
static SharedPtr< Graphics > FromImage(const SharedPtr< Image > &image)
static int DivRem(int a, int b, int &result)

◆ RenderToSize()

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

Renders a document page into a Graphics 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

Render 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);
// User has some sort of a Graphics object. In this case created from a bitmap
{
SharedPtr<System::Drawing::Graphics> gr = System::Drawing::Graphics::FromImage(bmp);
// The user can specify any options on the Graphics object including
// transform, anti-aliasing, page units, etc.
// If we want to fit the page into a 3" x 3" square on the screen, we will need to set the measurement units to inches
// The output should be offset 0.5" from the edge and rotated
gr->TranslateTransform(0.5f, 0.5f);
gr->RotateTransform(10.0f);
// This is our test rectangle
gr->DrawRectangle(MakeObject<System::Drawing::Pen>(System::Drawing::Color::get_Black(), 3.f / 72.f), 0.f, 0.f, 3.f, 3.f);
// User specifies (in world coordinates) where on the Graphics to render and what size
float returnedScale = doc->RenderToSize(0, gr, 0.f, 0.f, 3.f, 3.f);
// This is the calculated scale factor to fit 297mm into 3"
std::cout << String::Format(u"The image was rendered at {0:P0} zoom.", returnedScale) << std::endl;
// One more example, this time in millimeters
gr->ResetTransform();
// Move the origin 10mm
gr->TranslateTransform(10.0f, 10.0f);
// Apply both scale transform and page scale for fun
gr->ScaleTransform(0.5f, 0.5f);
gr->set_PageScale(2.f);
// This is our test rectangle
gr->DrawRectangle(MakeObject<System::Drawing::Pen>(System::Drawing::Color::get_Black(), 1.0f), 90, 10, 50, 100);
// User specifies (in world coordinates) where on the Graphics to render and what size
doc->RenderToSize(1, gr, 90.0f, 10.0f, 50.0f, 100.0f);
bmp->Save(ArtifactsDir + u"Rendering.RenderToSize.png");
}
}

◆ Save() [1/5]

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 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());
}
@ Docx
Saves the document as an Office Open XML WordprocessingML Document (macro-free).

Shows how to save a document to the JPEG format using the Save method and the ImageSaveOptions class.

// Open the document
auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
// Save as a JPEG image file with default options
doc->Save(ArtifactsDir + u"Rendering.SaveAsImage.DefaultJpgOptions.jpg");
// Save document to stream as a JPEG with default options
auto docStream = MakeObject<System::IO::MemoryStream>();
doc->Save(docStream, SaveFormat::Jpeg);
// Rewind the stream position back to the beginning, ready for use
docStream->Seek(static_cast<int64_t>(0), System::IO::SeekOrigin::Begin);
// Save document to a JPEG image with specified options
// Render the third page only and set the JPEG quality to 80%
// In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
// to signal what type of image to save as
auto imageOptions = MakeObject<ImageSaveOptions>(SaveFormat::Jpeg);
imageOptions->set_PageIndex(2);
imageOptions->set_PageCount(1);
imageOptions->set_JpegQuality(80);
doc->Save(ArtifactsDir + u"Rendering.SaveAsImage.CustomJpgOptions.jpg", imageOptions);
@ Jpeg
Renders a page of the document and saves it as a JPEG file.

Saves a document page as a BMP image into a stream.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
auto stream = MakeObject<System::IO::MemoryStream>();
doc->Save(stream, SaveFormat::Bmp);
// Rewind the stream and create a .NET image from it
stream->set_Position(0);
// Read the stream back into an image
{
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromStream(stream);
// ...Do something
}
static SharedPtr< Image > FromStream(const SharedPtr< System::IO::Stream > &stream, bool use_embedded_color_management=false, bool validate_image_data=true)
@ Bmp
Renders a page of the document and saves it as a BMP file.

◆ Save() [2/5]

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.

◆ Save() [3/5]

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

Shows how to save a document to the JPEG format using the Save method and the ImageSaveOptions class.

// Open the document
auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
// Save as a JPEG image file with default options
doc->Save(ArtifactsDir + u"Rendering.SaveAsImage.DefaultJpgOptions.jpg");
// Save document to stream as a JPEG with default options
auto docStream = MakeObject<System::IO::MemoryStream>();
doc->Save(docStream, SaveFormat::Jpeg);
// Rewind the stream position back to the beginning, ready for use
docStream->Seek(static_cast<int64_t>(0), System::IO::SeekOrigin::Begin);
// Save document to a JPEG image with specified options
// Render the third page only and set the JPEG quality to 80%
// In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
// to signal what type of image to save as
auto imageOptions = MakeObject<ImageSaveOptions>(SaveFormat::Jpeg);
imageOptions->set_PageIndex(2);
imageOptions->set_PageCount(1);
imageOptions->set_JpegQuality(80);
doc->Save(ArtifactsDir + u"Rendering.SaveAsImage.CustomJpgOptions.jpg", imageOptions);

◆ Save() [4/5]

System::SharedPtr<Aspose::Words::Saving::SaveOutputParameters> Aspose::Words::Document::Save ( 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);
@ Html
Saves the document in the HTML format.

◆ Save() [5/5]

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

Converts a whole document to PDF with three levels in the document outline.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
auto options = MakeObject<PdfSaveOptions>();
options->get_OutlineOptions()->set_HeadingsOutlineLevels(3);
options->get_OutlineOptions()->set_ExpandedOutlineLevels(1);
doc->Save(ArtifactsDir + u"Rendering.SaveToPdfWithOutline.pdf", options);

Shows how to save a document to the JPEG format using the Save method and the ImageSaveOptions class.

// Open the document
auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
// Save as a JPEG image file with default options
doc->Save(ArtifactsDir + u"Rendering.SaveAsImage.DefaultJpgOptions.jpg");
// Save document to stream as a JPEG with default options
auto docStream = MakeObject<System::IO::MemoryStream>();
doc->Save(docStream, SaveFormat::Jpeg);
// Rewind the stream position back to the beginning, ready for use
docStream->Seek(static_cast<int64_t>(0), System::IO::SeekOrigin::Begin);
// Save document to a JPEG image with specified options
// Render the third page only and set the JPEG quality to 80%
// In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
// to signal what type of image to save as
auto imageOptions = MakeObject<ImageSaveOptions>(SaveFormat::Jpeg);
imageOptions->set_PageIndex(2);
imageOptions->set_PageCount(1);
imageOptions->set_JpegQuality(80);
doc->Save(ArtifactsDir + u"Rendering.SaveAsImage.CustomJpgOptions.jpg", imageOptions);

Converts every page of a DOC file into a separate scalable EMF file.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
auto options = MakeObject<ImageSaveOptions>(SaveFormat::Emf);
options->set_PageCount(1);
for (int i = 0; i < doc->get_PageCount(); i++)
{
options->set_PageIndex(i);
doc->Save(ArtifactsDir + u"Rendering.SaveToEmf." + i + u".emf", options);
}
@ Emf
Renders a page of the document and saves it as a vector EMF (Enhanced Meta File) file.

◆ set_AttachedTemplate()

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

◆ set_AutomaticallyUpdateStyles()

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

◆ set_CustomXmlParts()

void Aspose::Words::Document::set_CustomXmlParts ( 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 ( System::SharedPtr< Aspose::Words::Fonts::FontSettings value)

◆ set_GlossaryDocument()

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

◆ set_GrammarChecked()

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

Returns true if the document has been checked for grammar.

◆ set_MailMergeSettings()

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

◆ set_PackageCustomParts()

void Aspose::Words::Document::set_PackageCustomParts ( 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)

Returns true if the document has been checked for spelling.

◆ set_TrackRevisions()

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

◆ set_VbaProject()

void Aspose::Words::Document::set_VbaProject ( System::SharedPtr< Aspose::Words::VbaProject value)

◆ StartTrackRevisions() [1/2]

void Aspose::Words::Document::StartTrackRevisions ( 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, they can be processed via Review -> Changes.
doc->Save(ArtifactsDir + u"Document.StartTrackRevisions.docx");
static const DateTime MinValue

◆ StartTrackRevisions() [2/2]

void Aspose::Words::Document::StartTrackRevisions ( 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, they can be processed 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, they can be processed 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 ( 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 will create an entry in the table, as long as its heading level is between 1 and 3.
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");
@ Heading4
The Heading 4 style.
@ Heading3
The Heading 3 style.
@ Heading2
The Heading 2 style.

Shows to use the QUOTE field.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a QUOTE field, which will display content from the Text attribute
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 with a nested DATE field
// DATE fields normally update their value to the current date every time the document is opened
// 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());
// Some field types don't display the correct result until they are manually updated
ASSERT_EQ(String::Empty, doc->get_Range()->get_Fields()->idx_get(0)->get_Result());
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 with fields.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Set 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 fields that reference our user information
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 value that fields from many 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.FieldOptionsCurrentUser.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 label of each paragraph in a list as a value or a String.

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 actually getting when we output this node to text format
// The list labels are not included in this text output. Trim any paragraph formatting characters
String paragraphText = paragraph->ToString(SaveFormat::Text).Trim();
std::cout << "\tExported Text: " << paragraphText << std::endl;
SharedPtr<ListLabel> label = paragraph->get_ListLabel();
// This gets the position of the paragraph in 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;
}
@ Text
Saves the document in the plain text format.

◆ 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 request page layout of the document to be recalculated.

auto doc = MakeObject<Document>(MyDir + u"Rendering.docx");
// Saving a document to PDF or to image or printing for the first time will automatically
// layout document pages and this information will be cached inside the document
doc->Save(ArtifactsDir + u"Rendering.UpdatePageLayout.1.pdf");
// Modify the document in any 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 you want to save to PDF or render a modified document again,
// you need to manually request page layout to be updated
doc->UpdatePageLayout();
doc->Save(ArtifactsDir + u"Rendering.UpdatePageLayout.2.pdf");
@ Landscape
Landscape page orientation (wide and short).

◆ 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();
// Create a SaveOptions object to prepare this document to be saved to .txt.
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 ( 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());