Aspose::Words::DocumentBase Class Referenceabstract

Detailed Description

Provides the abstract base class for a main document and a glossary document of a Word document.

Aspose.Words represents a Word document as a tree of nodes. DocumentBase is a root node of the tree that contains all other nodes of the document.

DocumentBase also stores document-wide information such as Styles and Lists that the tree nodes might refer to.

See also
Aspose::Words::Document
Aspose::Words::DocumentBase
Examples

Shows how to initialize the subclasses of DocumentBase.

// DocumentBase is the abstract base class for the Document and GlossaryDocument classes
auto doc = MakeObject<Document>();
auto glossaryDoc = MakeObject<GlossaryDocument>();
doc->set_GlossaryDocument(glossaryDoc);

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

+ Inheritance diagram for Aspose::Words::DocumentBase:

Public Member Functions

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...
 
virtual const TypeInfoGetType () const override
 
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...
 
virtual bool Is (const TypeInfo &target) const override
 
void set_BackgroundShape (SharedPtr< Shape > value)
 Setter for get_BackgroundShape. More...
 
void set_NodeChangingCallback (SharedPtr< INodeChangingCallback > value)
 Called when a node is inserted or removed in the document. More...
 
void set_PageColor (Color value)
 Setter for get_PageColor. More...
 
void set_ResourceLoadingCallback (SharedPtr< IResourceLoadingCallback > value)
 Allows to control how external resources are loaded. 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
virtual bool Accept (SharedPtr< DocumentVisitor > visitor)=0
 Accepts a visitor. More...
 
SharedPtr< NodeClone (bool isCloneChildren)
 
SharedPtr< Nodeget_NextSibling ()
 Gets the node immediately following this node. More...
 
virtual NodeType get_NodeType () const =0
 Gets the type of 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...
 
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
ASPOSECPP_SHARED_API Object ()
 
ASPOSECPP_SHARED_API Object (Object const &x)
 
virtual ASPOSECPP_SHARED_API ~Object ()
 
virtual ASPOSECPP_SHARED_API bool Equals (ptr obj)
 
Detail::SmartPtrCounter * GetCounter ()
 
virtual ASPOSECPP_SHARED_API int GetHashCode () const
 
ASPOSECPP_SHARED_API void Lock ()
 
virtual ASPOSECPP_SHARED_API 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 ASPOSECPP_SHARED_API void SetTemplateWeakPtr (unsigned int argument)
 
int SharedCount () const
 
ObjectSharedRefAdded ()
 
int SharedRefRemovedSafe ()
 
virtual ASPOSECPP_SHARED_API String ToString () const
 
ASPOSECPP_SHARED_API void Unlock ()
 
Detail::SmartPtrCounter * WeakRefAdded ()
 
void WeakRefRemoved ()
 
- Public Member Functions inherited from System::Collections::Generic::IEnumerable< System::SharedPtr< Aspose::Words::Node > >
EnumeratorBasedIterator< T, IEnumerator< T > > begin () noexcept
 
EnumeratorBasedIterator< T, IEnumerator< T > > cbegin () noexcept
 
EnumeratorBasedIterator< T, IEnumerator< T > > cend () noexcept
 
EnumeratorBasedIterator< T, IEnumerator< T > > 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 ()
 
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 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 IEnumerator< T > IEnumeratorType
 
typedef T ValueType
 

Member Function Documentation

◆ get_BackgroundShape()

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBase::get_BackgroundShape ( ) const

Gets or sets the background shape of the document. Can be null.

Microsoft Word allows only a shape that has its ShapeType property equal to Rectangle to be used as a background shape for a document.

Microsoft Word supports only the fill properties of a background shape. All other properties are ignored.

Setting this property to a non-null value will also set the DisplayBackgroundShape to true.

See also
Aspose::Words::Settings::ViewOptions::get_DisplayBackgroundShape
Aspose::Words::DocumentBase::get_PageColor
Examples

Shows how to set the background shape of a document.

auto doc = MakeObject<Document>();
ASSERT_TRUE(doc->get_BackgroundShape() == nullptr);
// A background shape can only be a rectangle
// We will set the color of this rectangle to light blue
auto shapeRectangle = MakeObject<Shape>(doc, ShapeType::Rectangle);
doc->set_BackgroundShape(shapeRectangle);
// This rectangle covers the entire page in the output document
// We can also do this by setting doc.PageColor
shapeRectangle->set_FillColor(System::Drawing::Color::get_LightBlue());
doc->Save(ArtifactsDir + u"DocumentBase.BackgroundShapeFlatColor.docx");
// Setting the image will override the flat background color with the image
shapeRectangle->get_ImageData()->SetImage(ImageDir + u"Transparent background logo.png");
ASSERT_TRUE(doc->get_BackgroundShape()->get_HasImage());
// This image is a photo with a white background
// To make it suitable as a watermark, we will need to do some image processing
// The default values for these variables are 0.5, so here we are lowering the contrast and increasing the brightness
shapeRectangle->get_ImageData()->set_Contrast(0.2);
shapeRectangle->get_ImageData()->set_Brightness(0.7);
// Microsoft Word does not support images in background shapes, so even though we set the background as an image,
// the output will show a light blue background like before
// However, we can see our watermark in an output pdf
doc->Save(ArtifactsDir + u"DocumentBase.BackgroundShape.pdf");

◆ get_Document()

System::SharedPtr<Aspose::Words::DocumentBase> Aspose::Words::DocumentBase::get_Document ( ) const
overridevirtual

Gets the document to which this node belongs.

The node always belongs to a document even if it has just been created and not yet added to the tree, or if it has been removed from the tree.

Examples

Shows how to create a node and set its owning document.

// Open a file from disk
auto doc = MakeObject<Document>();
// Creating a new node of any type requires a document passed into the constructor
auto para = MakeObject<Paragraph>(doc);
// The new paragraph node does not yet have a parent
System::Console::WriteLine(String(u"Paragraph has no parent node: ") + (para->get_ParentNode() == nullptr));
// But the paragraph node knows its document
System::Console::WriteLine(String(u"Both nodes' documents are the same: ") + (para->get_Document() == doc));
// The fact that a node always belongs to a document allows us to access and modify
// properties that reference the document-wide data such as styles or lists
para->get_ParagraphFormat()->set_StyleName(u"Heading 1");
// Now add the paragraph to the main text of the first section
doc->get_FirstSection()->get_Body()->AppendChild(para);
// The paragraph node is now a child of the Body node
System::Console::WriteLine(String(u"Paragraph has a parent node: ") + (para->get_ParentNode() != nullptr));

Reimplemented from Aspose::Words::Node.

◆ get_FontInfos()

System::SharedPtr<Aspose::Words::Fonts::FontInfoCollection> Aspose::Words::DocumentBase::get_FontInfos ( ) const

Provides access to properties of fonts used in this document.

This collection of font definitions is loaded as is from the document. Font definitions might be optional, missing or incomplete in some documents.

Do not rely on this collection to ascertain that a particular font is used in the document. You should only use this collection to get information about fonts that might be used in the document.

See also
Aspose::Words::Fonts::FontInfoCollection
Aspose::Words::Fonts::FontInfo
Examples

Shows how to print the details of what fonts are present in a document.

auto doc = MakeObject<Document>(MyDir + u"Embedded font.docx");
SharedPtr<FontInfoCollection> fonts = doc->get_FontInfos();
// The fonts info extracted from this document does not necessarily mean that the fonts themselves are
// used in the document. If a font is present but not used then most likely they were referenced at some time
// and then removed from the Document
for (int i = 0; i < fonts->get_Count(); i++)
{
System::Console::WriteLine(String::Format(u"Font index #{0}", i));
System::Console::WriteLine(String::Format(u"\tName: {0}", fonts->idx_get(i)->get_Name()));
System::Console::WriteLine(String::Format(u"\tIs {0}a trueType font", (fonts->idx_get(i)->get_IsTrueType() ? String(u"") : String(u"not "))));
}

Shows how to save a document with embedded TrueType fonts.

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
SharedPtr<FontInfoCollection> fontInfos = doc->get_FontInfos();
fontInfos->set_EmbedTrueTypeFonts(true);
fontInfos->set_EmbedSystemFonts(false);
fontInfos->set_SaveSubsetFonts(false);
doc->Save(ArtifactsDir + u"Font.FontInfoCollection.docx");

◆ get_Lists()

System::SharedPtr<Aspose::Words::Lists::ListCollection> Aspose::Words::DocumentBase::get_Lists ( ) const

Provides access to the list formatting used in the document.

For more information see the description of the ListCollection class.

See also
Aspose::Words::Lists::ListCollection
Aspose::Words::Lists::List
Aspose::Words::ListFormat
Examples

Shows how to specify list level number when building a list using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder
builder->get_ListFormat()->set_List(doc->get_Lists()->Add(ListTemplate::NumberArabicDot));
// Insert text at each of the 9 indent levels
for (int i = 0; i < 9; i++)
{
builder->get_ListFormat()->set_ListLevelNumber(i);
builder->Writeln(String(u"Level ") + i);
}
// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder
builder->get_ListFormat()->set_List(doc->get_Lists()->Add(ListTemplate::BulletDiamonds));
for (int i = 0; i < 9; i++)
{
builder->get_ListFormat()->set_ListLevelNumber(i);
builder->Writeln(String(u"Level ") + i);
}
// This is a way to stop list formatting
builder->get_ListFormat()->set_List(nullptr);
doc->Save(ArtifactsDir + u"Lists.SpecifyListLevel.docx");

◆ get_NodeChangingCallback()

System::SharedPtr<Aspose::Words::INodeChangingCallback> Aspose::Words::DocumentBase::get_NodeChangingCallback ( )

Called when a node is inserted or removed in the document.

◆ get_PageColor()

System::Drawing::Color Aspose::Words::DocumentBase::get_PageColor ( )

Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.

This property provides a simple way to specify a solid page color for the document. Setting this property creates and sets an appropriate BackgroundShape.

If the page color is not set (e.g. there is no background shape in the document) returns Empty.

See also
Aspose::Words::DocumentBase::get_BackgroundShape
Examples

Shows how to set the page color.

auto doc = MakeObject<Document>();
doc->Save(ArtifactsDir + u"DocumentBase.SetPageColor.docx");

◆ get_ResourceLoadingCallback()

System::SharedPtr<Aspose::Words::Loading::IResourceLoadingCallback> Aspose::Words::DocumentBase::get_ResourceLoadingCallback ( ) const

Allows to control how external resources are loaded.

◆ get_Styles()

System::SharedPtr<Aspose::Words::StyleCollection> Aspose::Words::DocumentBase::get_Styles ( ) const

Returns a collection of styles defined in the document.

For more information see the description of the StyleCollection class.

See also
Aspose::Words::StyleCollection
Aspose::Words::Style
Examples

Shows how to access a document's style collection.

auto doc = MakeObject<Document>();
// A blank document comes with 4 styles by default
ASSERT_EQ(4, doc->get_Styles()->get_Count());
{
SharedPtr<System::Collections::Generic::IEnumerator<SharedPtr<Style>>> stylesEnum = doc->get_Styles()->GetEnumerator();
while (stylesEnum->MoveNext())
{
SharedPtr<Style> curStyle = stylesEnum->get_Current();
System::Console::WriteLine(String::Format(u"Style name:\t\"{0}\", of type \"{1}\"", curStyle->get_Name(), curStyle->get_Type()));
System::Console::WriteLine(String::Format(u"\tSubsequent style:\t{0}", curStyle->get_NextParagraphStyleName()));
System::Console::WriteLine(String::Format(u"\tIs heading:\t\t\t{0}", curStyle->get_IsHeading()));
System::Console::WriteLine(String::Format(u"\tIs QuickStyle:\t\t{0}", curStyle->get_IsQuickStyle()));
ASPOSE_ASSERT_EQ(doc, curStyle->get_Document());
}
}

Shows how to create and use a paragraph style with list formatting.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a paragraph style and specify some formatting for it
SharedPtr<Style> style = doc->get_Styles()->Add(StyleType::Paragraph, u"MyStyle1");
style->get_Font()->set_Size(24);
style->get_Font()->set_Name(u"Verdana");
style->get_ParagraphFormat()->set_SpaceAfter(12);
// Create a list and make sure the paragraphs that use this style will use this list
style->get_ListFormat()->set_List(doc->get_Lists()->Add(ListTemplate::BulletDefault));
style->get_ListFormat()->set_ListLevelNumber(0);
// Apply the paragraph style to the current paragraph in the document and add some text
builder->get_ParagraphFormat()->set_Style(style);
builder->Writeln(u"Hello World: MyStyle1, bulleted list.");
// Change to a paragraph style that has no list formatting
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Normal"));
builder->Writeln(u"Hello World: Normal.");
builder->get_Document()->Save(ArtifactsDir + u"Styles.ParagraphStyleBulletedList.docx");

◆ get_WarningCallback()

System::SharedPtr<Aspose::Words::IWarningCallback> Aspose::Words::DocumentBase::get_WarningCallback ( ) const

Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.

Examples

Demonstrates how to receive notifications of font substitutions by using IWarningCallback.

// Load the document to render
auto doc = MakeObject<Document>(MyDir + u"Document.docx");
// Create a new class implementing IWarningCallback and assign it to the PdfSaveOptions class
auto callback = MakeObject<ExFont::HandleDocumentSubstitutionWarnings>();
doc->set_WarningCallback(callback);
// We can choose the default font to use in the case of any missing fonts
FontSettings::get_DefaultInstance()->get_SubstitutionSettings()->get_DefaultFontSubstitution()->set_DefaultFontName(u"Arial");
// For testing we will set Aspose.Words to look for fonts only in a folder which doesn't exist. Since Aspose.Words won't
// find any fonts in the specified directory, then during rendering the fonts in the document will be substituted with the default
// font specified under FontSettings.DefaultFontName. We can pick up on this substitution using our callback
FontSettings::get_DefaultInstance()->SetFontsFolder(String::Empty, false);
// Pass the save options along with the save path to the save method
doc->Save(ArtifactsDir + u"Font.SubstitutionNotification.pdf");

◆ GetType()

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

◆ ImportNode() [1/2]

System::SharedPtr<Aspose::Words::Node> Aspose::Words::DocumentBase::ImportNode ( System::SharedPtr< Aspose::Words::Node srcNode,
bool  isImportChildren 
)

Imports a node from another document to the current document.

This method uses the UseDestinationStyles option to resolve formatting.

Importing a node creates a copy of the source node belonging to the importing document. The returned node has no parent. The source node is not altered or removed from the original document.

Before a node from another document can be inserted into this document, it must be imported. During import, document-specific properties such as references to styles and lists are translated from the original to the importing document. After the node was imported, it can be inserted into the appropriate place in the document using InsertBefore() or InsertAfter().

If the source node already belongs to the destination document, then simply a deep clone of the source node is created.

Parameters
srcNodeThe node being imported.
isImportChildrenTrue to import all child nodes recursively; otherwise, false.
Returns
The cloned node that belongs to the current document.
See also
Aspose::Words::NodeImporter
Examples

Shows how to import node from source document to destination document.

auto src = MakeObject<Document>();
auto dst = MakeObject<Document>();
// Add text to both documents
src->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(MakeObject<Run>(src, u"Source document first paragraph text."));
dst->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(MakeObject<Run>(dst, u"Destination document first paragraph text."));
// In order for a child node to be successfully appended to another node in a document,
// both nodes must have the same parent document, or an exception is thrown
ASPOSE_ASSERT_NE(dst, src->get_FirstSection()->get_Document());
auto appendSection = [&dst, &src]()
{
dst->AppendChild(src->get_FirstSection());
};
ASSERT_THROW(appendSection(), System::ArgumentException);
// For that reason, we can't just append a section of the source document to the destination document using Node.AppendChild()
// Document.ImportNode() lets us get around this by creating a clone of a node and sets its parent to the calling document
auto importedSection = System::DynamicCast<Section>(dst->ImportNode(src->get_FirstSection(), true));
// Now it is ready to be placed in the document
dst->AppendChild(importedSection);
// Our document now contains both the original and imported section
ASSERT_EQ(u"Destination document first paragraph text.\r\nSource document first paragraph text.\r\n", dst->ToString(SaveFormat::Text));

◆ ImportNode() [2/2]

System::SharedPtr<Aspose::Words::Node> Aspose::Words::DocumentBase::ImportNode ( System::SharedPtr< Aspose::Words::Node srcNode,
bool  isImportChildren,
Aspose::Words::ImportFormatMode  importFormatMode 
)

Imports a node from another document to the current document with an option to control formatting.

This overload is useful to control how styles and list formatting are imported.

Importing a node creates a copy of the source node belonging to the importing document. The returned node has no parent. The source node is not altered or removed from the original document.

Before a node from another document can be inserted into this document, it must be imported. During import, document-specific properties such as references to styles and lists are translated from the original to the importing document. After the node was imported, it can be inserted into the appropriate place in the document using InsertBefore() or InsertAfter().

If the source node already belongs to the destination document, then simply a deep clone of the source node is created.

Parameters
srcNodeThe node to imported.
isImportChildrenTrue to import all child nodes recursively; otherwise, false.
importFormatModeSpecifies how to merge style formatting that clashes.
Returns
The cloned, imported node. The node belongs to the destination document, but has no parent.
See also
Aspose::Words::ImportFormatMode
Aspose::Words::NodeImporter
Examples

Shows how to import node from source document to destination document with specific options.

// Create two documents with two styles that differ in font but have the same name
auto src = MakeObject<Document>();
SharedPtr<Style> srcStyle = src->get_Styles()->Add(StyleType::Character, u"My style");
srcStyle->get_Font()->set_Name(u"Courier New");
auto srcBuilder = MakeObject<DocumentBuilder>(src);
srcBuilder->get_Font()->set_Style(srcStyle);
srcBuilder->Writeln(u"Source document text.");
auto dst = MakeObject<Document>();
SharedPtr<Style> dstStyle = dst->get_Styles()->Add(StyleType::Character, u"My style");
dstStyle->get_Font()->set_Name(u"Calibri");
auto dstBuilder = MakeObject<DocumentBuilder>(dst);
dstBuilder->get_Font()->set_Style(dstStyle);
dstBuilder->Writeln(u"Destination document text.");
// Import the Section from the destination document into the source document, causing a style name collision
// If we use destination styles then the imported source text with the same style name as destination text
// will adopt the destination style
auto importedSection = System::DynamicCast<Section>(dst->ImportNode(src->get_FirstSection(), true, ImportFormatMode::UseDestinationStyles));
ASSERT_EQ(dstStyle->get_Font()->get_Name(), importedSection->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)->get_Font()->get_Name());
ASSERT_EQ(dstStyle->get_Name(), importedSection->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)->get_Font()->get_StyleName());
// If we use ImportFormatMode.KeepDifferentStyles,
// the source style is preserved and the naming clash is resolved by adding a suffix
dst->ImportNode(src->get_FirstSection(), true, ImportFormatMode::KeepDifferentStyles);
ASSERT_EQ(dstStyle->get_Font()->get_Name(), dst->get_Styles()->idx_get(u"My style")->get_Font()->get_Name());
ASSERT_EQ(srcStyle->get_Font()->get_Name(), dst->get_Styles()->idx_get(u"My style_0")->get_Font()->get_Name());

◆ Is()

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

◆ set_BackgroundShape()

void Aspose::Words::DocumentBase::set_BackgroundShape ( System::SharedPtr< Aspose::Words::Drawing::Shape value)

◆ set_NodeChangingCallback()

void Aspose::Words::DocumentBase::set_NodeChangingCallback ( System::SharedPtr< Aspose::Words::INodeChangingCallback value)

Called when a node is inserted or removed in the document.

◆ set_PageColor()

void Aspose::Words::DocumentBase::set_PageColor ( System::Drawing::Color  value)

◆ set_ResourceLoadingCallback()

void Aspose::Words::DocumentBase::set_ResourceLoadingCallback ( System::SharedPtr< Aspose::Words::Loading::IResourceLoadingCallback value)

Allows to control how external resources are loaded.

◆ set_WarningCallback()

void Aspose::Words::DocumentBase::set_WarningCallback ( System::SharedPtr< Aspose::Words::IWarningCallback value)

◆ Type()

static const System::TypeInfo& Aspose::Words::DocumentBase::Type ( )
static
String
@ KeepDifferentStyles
Only copy styles that are different from those in the source document.
@ Character
The style is a character style.
@ Text
Saves the document in the plain text format.
static ASPOSECPP_SHARED_API void WriteLine()
@ UseDestinationStyles
Use the destination document styles and copy new styles. This is the default option.
@ Paragraph
The style is a paragraph style.
static ASPOSECPP_SHARED_API Color get_LightGray()
static ASPOSECPP_SHARED_API Color get_LightBlue()