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.

auto doc = MakeObject<Document>();
ASPOSE_ASSERT_EQ(System::ObjectExt::GetType<DocumentBase>(), System::ObjectExt::GetType(doc).get_BaseType());
auto glossaryDoc = MakeObject<GlossaryDocument>();
doc->set_GlossaryDocument(glossaryDoc);
ASPOSE_ASSERT_EQ(System::ObjectExt::GetType<DocumentBase>(), System::ObjectExt::GetType(glossaryDoc).get_BaseType());

#include <Aspose.Words.Cpp/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 (const SharedPtr< Node > &srcNode, bool isImportChildren)
 Imports a node from another document to the current document. More...
 
SharedPtr< NodeImportNode (const SharedPtr< Node > &srcNode, bool isImportChildren, ImportFormatMode importFormatMode)
 Imports a node from another document to the current document with an option to control formatting. More...
 
virtual bool Is (const TypeInfo &target) const override
 
void set_BackgroundShape (const SharedPtr< Shape > &value)
 Setter for get_BackgroundShape. More...
 
void set_NodeChangingCallback (const SharedPtr< INodeChangingCallback > &value)
 Setter for get_NodeChangingCallback. More...
 
void set_PageColor (Color value)
 Setter for get_PageColor. More...
 
void set_ResourceLoadingCallback (const SharedPtr< IResourceLoadingCallback > &value)
 Setter for get_ResourceLoadingCallback. More...
 
void set_WarningCallback (const SharedPtr< IWarningCallback > &value)
 Setter for get_WarningCallback. More...
 
- Public Member Functions inherited from CompositeNode
SharedPtr< NodeAppendChild (const SharedPtr< Node > &newChild)
 Adds the specified node to the end of the list of child nodes for this node. More...
 
SharedPtr< NodeCollectionget_ChildNodes ()
 Gets all immediate child nodes of this node. More...
 
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 (const SharedPtr< Node > &child)
 Returns the index of the specified child node in the child node array. More...
 
SharedPtr< NodeInsertAfter (const SharedPtr< Node > &newChild, const SharedPtr< Node > &refChild)
 Inserts the specified node immediately after the specified reference node. More...
 
SharedPtr< NodeInsertBefore (const SharedPtr< Node > &newChild, const SharedPtr< Node > &refChild)
 Inserts the specified node immediately before the specified reference node. More...
 
SharedPtr< NodePrependChild (const SharedPtr< Node > &newChild)
 Adds the specified node to the beginning of the list of child nodes for this node. More...
 
void RemoveAllChildren ()
 Removes all the child nodes of the current node. More...
 
SharedPtr< NodeRemoveChild (const SharedPtr< Node > &oldChild)
 Removes the specified child node. More...
 
void RemoveSmartTags ()
 Removes all SmartTag descendant nodes of the current node. More...
 
SharedPtr< NodeListSelectNodes (const String &xpath)
 Selects a list of nodes matching the XPath expression. More...
 
SharedPtr< NodeSelectSingleNode (const String &xpath)
 Selects the first Node that matches the XPath expression. More...
 
- Public Member Functions inherited from Node
virtual bool Accept (SharedPtr< DocumentVisitor > visitor)=0
 Accepts a visitor. More...
 
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...
 
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 (const SharedPtr< Node > &rootNode)
 Gets next node according to the pre-order tree traversal algorithm. More...
 
SharedPtr< NodePreviousPreOrder (const SharedPtr< Node > &rootNode)
 Gets the previous node according to the pre-order tree traversal algorithm. More...
 
void Remove ()
 Removes itself from the parent. More...
 
void set_CustomNodeId (int32_t value)
 Setter for get_CustomNodeId. More...
 
String ToString (SaveFormat saveFormat)
 Exports the content of the node into a string in the specified format. More...
 
String ToString (const SharedPtr< SaveOptions > &saveOptions)
 Exports the content of the node into a string using the specified save options. More...
 

Static Public Member Functions

static const TypeInfoType ()
 
- Static Public Member Functions inherited from 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 ()
 

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 a background shape for every page of a document.

auto doc = MakeObject<Document>();
ASSERT_TRUE(doc->get_BackgroundShape() == nullptr);
// The only shape type that we can use as a background is a rectangle.
auto shapeRectangle = MakeObject<Shape>(doc, ShapeType::Rectangle);
// There are two ways of using this shape as a page background.
// 1 - A flat color:
shapeRectangle->set_FillColor(System::Drawing::Color::get_LightBlue());
doc->set_BackgroundShape(shapeRectangle);
doc->Save(ArtifactsDir + u"DocumentBase.BackgroundShape.FlatColor.docx");
// 2 - An image:
shapeRectangle = MakeObject<Shape>(doc, ShapeType::Rectangle);
shapeRectangle->get_ImageData()->SetImage(ImageDir + u"Transparent background logo.png");
// Adjust the image's appearance to make it more suitable as a watermark.
shapeRectangle->get_ImageData()->set_Contrast(0.2);
shapeRectangle->get_ImageData()->set_Brightness(0.7);
doc->set_BackgroundShape(shapeRectangle);
ASSERT_TRUE(doc->get_BackgroundShape()->get_HasImage());
// Microsoft Word does not support shapes with images as backgrounds,
// but we can still see these backgrounds in other save formats such as .pdf.
doc->Save(ArtifactsDir + u"DocumentBase.BackgroundShape.Image.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.

auto doc = MakeObject<Document>();
auto para = MakeObject<Paragraph>(doc);
para->AppendChild(MakeObject<Run>(doc, u"Hello world!"));
// We have not yet appended this paragraph as a child to any composite node.
ASSERT_TRUE(para->get_ParentNode() == nullptr);
// If a node is an appropriate child node type of another composite node,
// we can attach it as a child only if both nodes have the same owner document.
// The owner document is the document we passed to the node's constructor.
// We have not attached this paragraph to the document, so the document does not contain its text.
ASPOSE_ASSERT_EQ(para->get_Document(), doc);
ASSERT_EQ(String::Empty, doc->GetText().Trim());
// Since the document owns this paragraph, we can apply one of its styles to the paragraph's contents.
para->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 1"));
// Add this node to the document, and then verify its contents.
doc->get_FirstSection()->get_Body()->AppendChild(para);
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body(), para->get_ParentNode());
ASSERT_EQ(u"Hello world!", doc->GetText().Trim());

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<Aspose::Words::Fonts::FontInfoCollection> allFonts = doc->get_FontInfos();
// Print all the used and unused fonts in the document.
for (int i = 0; i < allFonts->get_Count(); i++)
{
std::cout << "Font index #" << i << std::endl;
std::cout << "\tName: " << allFonts->idx_get(i)->get_Name() << std::endl;
std::cout << "\tIs " << (allFonts->idx_get(i)->get_IsTrueType() ? String(u"") : String(u"not ")) << "a trueType font" << std::endl;
}

Shows how to save a document with embedded TrueType fonts.

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
SharedPtr<Aspose::Words::Fonts::FontInfoCollection> fontInfos = doc->get_FontInfos();
fontInfos->set_EmbedTrueTypeFonts(embedAllFonts);
fontInfos->set_EmbedSystemFonts(embedAllFonts);
fontInfos->set_SaveSubsetFonts(embedAllFonts);
doc->Save(ArtifactsDir + u"Font.FontInfoCollection.docx");
if (embedAllFonts)
{
ASSERT_LT(25000, MakeObject<System::IO::FileInfo>(ArtifactsDir + u"Font.FontInfoCollection.docx")->get_Length());
}
else
{
ASSERT_GE(15000, MakeObject<System::IO::FileInfo>(ArtifactsDir + u"Font.FontInfoCollection.docx")->get_Length());
}

◆ 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::Lists::ListFormat
Examples

Shows how to work with list levels.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
ASSERT_FALSE(builder->get_ListFormat()->get_IsListItem());
// A list allows us to organize and decorate sets of paragraphs with prefix symbols and indents.
// We can create nested lists by increasing the indent level.
// We can begin and end a list by using a document builder's "ListFormat" property.
// Each paragraph that we add between a list's start and the end will become an item in the list.
// Below are two types of lists that we can create using a document builder.
// 1 - A numbered list:
// Numbered lists create a logical order for their paragraphs by numbering each item.
builder->get_ListFormat()->set_List(doc->get_Lists()->Add(ListTemplate::NumberDefault));
ASSERT_TRUE(builder->get_ListFormat()->get_IsListItem());
// By setting the "ListLevelNumber" property, we can increase the list level
// to begin a self-contained sub-list at the current list item.
// The Microsoft Word list template called "NumberDefault" uses numbers to create list levels for the first list level.
// Deeper list levels use letters and lowercase Roman numerals.
for (int i = 0; i < 9; i++)
{
builder->get_ListFormat()->set_ListLevelNumber(i);
builder->Writeln(String(u"Level ") + i);
}
// 2 - A bulleted list:
// This list will apply an indent and a bullet symbol ("•") before each paragraph.
// Deeper levels of this list will use different symbols, such as "■" and "○".
builder->get_ListFormat()->set_List(doc->get_Lists()->Add(ListTemplate::BulletDefault));
for (int i = 0; i < 9; i++)
{
builder->get_ListFormat()->set_ListLevelNumber(i);
builder->Writeln(String(u"Level ") + i);
}
// We can disable list formatting to not format any subsequent paragraphs as lists by un-setting the "List" flag.
builder->get_ListFormat()->set_List(nullptr);
ASSERT_FALSE(builder->get_ListFormat()->get_IsListItem());
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.

Examples

Shows how customize node changing with a callback.

void FontChangeViaCallback()
{
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Set the node changing callback to custom implementation,
// then add/remove nodes to get it to generate a log.
auto callback = MakeObject<ExDocument::HandleNodeChangingFontChanger>();
doc->set_NodeChangingCallback(callback);
builder->Writeln(u"Hello world!");
builder->Writeln(u"Hello again!");
builder->InsertField(u" HYPERLINK \"https://www.google.com/\" ");
builder->InsertShape(ShapeType::Rectangle, 300, 300);
doc->get_Range()->get_Fields()->idx_get(0)->Remove();
std::cout << callback->GetLog() << std::endl;
}
class HandleNodeChangingFontChanger : public INodeChangingCallback
{
public:
void NodeInserted(SharedPtr<NodeChangingArgs> args) override
{
mLog->AppendLine(String::Format(u"\tType:\t{0}", args->get_Node()->get_NodeType()));
mLog->AppendLine(String::Format(u"\tHash:\t{0}", System::ObjectExt::GetHashCode(args->get_Node())));
if (args->get_Node()->get_NodeType() == NodeType::Run)
{
SharedPtr<Aspose::Words::Font> font = (System::DynamicCast<Run>(args->get_Node()))->get_Font();
mLog->Append(String::Format(u"\tFont:\tChanged from \"{0}\" {1}pt", font->get_Name(), font->get_Size()));
font->set_Size(24);
font->set_Name(u"Arial");
mLog->AppendLine(String::Format(u" to \"{0}\" {1}pt", font->get_Name(), font->get_Size()));
mLog->AppendLine(String::Format(u"\tContents:\n\t\t\"{0}\"", args->get_Node()->GetText()));
}
}
void NodeInserting(SharedPtr<NodeChangingArgs> args) override
{
mLog->AppendLine(String::Format(u"\n{0:dd/MM/yyyy HH:mm:ss:fff}\tNode insertion:", System::DateTime::get_Now()));
}
void NodeRemoved(SharedPtr<NodeChangingArgs> args) override
{
mLog->AppendLine(String::Format(u"\tType:\t{0}", args->get_Node()->get_NodeType()));
mLog->AppendLine(String::Format(u"\tHash code:\t{0}", System::ObjectExt::GetHashCode(args->get_Node())));
}
void NodeRemoving(SharedPtr<NodeChangingArgs> args) override
{
mLog->AppendLine(String::Format(u"\n{0:dd/MM/yyyy HH:mm:ss:fff}\tNode removal:", System::DateTime::get_Now()));
}
String GetLog()
{
return mLog->ToString();
}
HandleNodeChangingFontChanger() : mLog(MakeObject<System::Text::StringBuilder>())
{
}
private:
SharedPtr<System::Text::StringBuilder> mLog;
};

◆ 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 background color for all pages of a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello world!");
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.

Examples

Shows how to customize the process of loading external resources into a document.

void ResourceLoadingCallback()
{
auto doc = MakeObject<Document>();
doc->set_ResourceLoadingCallback(MakeObject<ExDocumentBase::ImageNameHandler>());
auto builder = MakeObject<DocumentBuilder>(doc);
// Images usually are inserted using a URI, or a byte array.
// Every instance of a resource load will call our callback's ResourceLoading method.
builder->InsertImage(u"Google logo");
builder->InsertImage(u"Aspose logo");
builder->InsertImage(u"Watermark");
ASSERT_EQ(3, doc->GetChildNodes(NodeType::Shape, true)->get_Count());
doc->Save(ArtifactsDir + u"DocumentBase.ResourceLoadingCallback.docx");
}
class ImageNameHandler : public IResourceLoadingCallback
{
public:
ResourceLoadingAction ResourceLoading(SharedPtr<ResourceLoadingArgs> args) override
{
// If this callback encounters one of the image shorthands while loading an image,
// it will apply unique logic for each defined shorthand instead of treating it as a URI.
if (args->get_ResourceType() == ResourceType::Image)
{
String imageUri = args->get_OriginalUri();
if (imageUri == u"Google logo")
{
{
auto webClient = MakeObject<System::Net::WebClient>();
args->SetData(webClient->DownloadData(u"http://www.google.com/images/logos/ps_logo2.png"));
}
return ResourceLoadingAction::UserProvided;
}
else if (imageUri == u"Aspose logo")
{
args->SetData(System::IO::File::ReadAllBytes(ImageDir + u"Logo.jpg"));
return ResourceLoadingAction::UserProvided;
}
else if (imageUri == u"Watermark")
{
args->SetData(System::IO::File::ReadAllBytes(ImageDir + u"Transparent background logo.png"));
return ResourceLoadingAction::UserProvided;
}
}
return ResourceLoadingAction::Default;
}
};

◆ 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>();
ASSERT_EQ(4, doc->get_Styles()->get_Count());
// Enumerate and list all the styles that a document created using Aspose.Words contains by default.
{
SharedPtr<System::Collections::Generic::IEnumerator<SharedPtr<Style>>> stylesEnum = doc->get_Styles()->GetEnumerator();
while (stylesEnum->MoveNext())
{
SharedPtr<Style> curStyle = stylesEnum->get_Current();
std::cout << String::Format(u"Style name:\t\"{0}\", of type \"{1}\"", curStyle->get_Name(), curStyle->get_Type()) << std::endl;
std::cout << "\tSubsequent style:\t" << curStyle->get_NextParagraphStyleName() << std::endl;
std::cout << String::Format(u"\tIs heading:\t\t\t{0}", curStyle->get_IsHeading()) << std::endl;
std::cout << String::Format(u"\tIs QuickStyle:\t\t{0}", curStyle->get_IsQuickStyle()) << std::endl;
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 custom paragraph style.
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 document builder's current paragraph, and then add some text.
builder->get_ParagraphFormat()->set_Style(style);
builder->Writeln(u"Hello World: MyStyle1, bulleted list.");
// Change the document builder's style to one that has no list formatting and write another paragraph.
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

Shows how to use the IWarningCallback interface to monitor font substitution warnings.

void SubstitutionWarning()
{
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Name(u"Times New Roman");
builder->Writeln(u"Hello world!");
auto callback = MakeObject<ExFontSettings::FontSubstitutionWarningCollector>();
doc->set_WarningCallback(callback);
// Store the current collection of font sources, which will be the default font source for every document
// for which we do not specify a different font source.
ArrayPtr<SharedPtr<FontSourceBase>> originalFontSources = FontSettings::get_DefaultInstance()->GetFontsSources();
// For testing purposes, we will set Aspose.Words to look for fonts only in a folder that does not exist.
FontSettings::get_DefaultInstance()->SetFontsFolder(String::Empty, false);
// When rendering the document, there will be no place to find the "Times New Roman" font.
// This will cause a font substitution warning, which our callback will detect.
doc->Save(ArtifactsDir + u"FontSettings.SubstitutionWarning.pdf");
FontSettings::get_DefaultInstance()->SetFontsSources(originalFontSources);
ASSERT_TRUE(callback->FontSubstitutionWarnings->idx_get(0)->get_WarningType() == WarningType::FontSubstitution);
ASSERT_TRUE(System::ObjectExt::Equals(callback->FontSubstitutionWarnings->idx_get(0)->get_Description(),
u"Font 'Times New Roman' has not been found. Using 'Fanwood' font instead. Reason: first available font."));
}
class FontSubstitutionWarningCollector : public IWarningCallback
{
public:
SharedPtr<WarningInfoCollection> FontSubstitutionWarnings;
void Warning(SharedPtr<WarningInfo> info) override
{
if (info->get_WarningType() == WarningType::FontSubstitution)
{
FontSubstitutionWarnings->Warning(info);
}
}
FontSubstitutionWarningCollector() : FontSubstitutionWarnings(MakeObject<WarningInfoCollection>())
{
}
};

Shows how to set the property for finding the closest match for a missing font from the available font sources.

void EnableFontSubstitution()
{
// Open a document that contains text formatted with a font that does not exist in any of our font sources.
auto doc = MakeObject<Document>(MyDir + u"Missing font.docx");
// Assign a callback for handling font substitution warnings.
auto substitutionWarningHandler = MakeObject<ExFontSettings::HandleDocumentSubstitutionWarnings>();
doc->set_WarningCallback(substitutionWarningHandler);
// Set a default font name and enable font substitution.
auto fontSettings = MakeObject<FontSettings>();
fontSettings->get_SubstitutionSettings()->get_DefaultFontSubstitution()->set_DefaultFontName(u"Arial");
;
fontSettings->get_SubstitutionSettings()->get_FontInfoSubstitution()->set_Enabled(true);
// We will get a font substitution warning if we save a document with a missing font.
doc->set_FontSettings(fontSettings);
doc->Save(ArtifactsDir + u"FontSettings.EnableFontSubstitution.pdf");
{
SharedPtr<System::Collections::Generic::IEnumerator<SharedPtr<WarningInfo>>> warnings = substitutionWarningHandler->FontWarnings->GetEnumerator();
while (warnings->MoveNext())
{
std::cout << warnings->get_Current()->get_Description() << std::endl;
}
}
// We can also verify warnings in the collection and clear them.
ASSERT_EQ(WarningSource::Layout, substitutionWarningHandler->FontWarnings->idx_get(0)->get_Source());
ASSERT_EQ(u"Font '28 Days Later' has not been found. Using 'Calibri' font instead. Reason: alternative name from document.",
substitutionWarningHandler->FontWarnings->idx_get(0)->get_Description());
substitutionWarningHandler->FontWarnings->Clear();
ASSERT_EQ(0, substitutionWarningHandler->FontWarnings->get_Count());
}
class HandleDocumentSubstitutionWarnings : public IWarningCallback
{
public:
SharedPtr<WarningInfoCollection> FontWarnings;
void Warning(SharedPtr<WarningInfo> info) override
{
if (info->get_WarningType() == WarningType::FontSubstitution)
{
FontWarnings->Warning(info);
}
}
HandleDocumentSubstitutionWarnings() : FontWarnings(MakeObject<WarningInfoCollection>())
{
}
};

◆ GetType()

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

◆ ImportNode() [1/2]

System::SharedPtr<Aspose::Words::Node> Aspose::Words::DocumentBase::ImportNode ( const 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 a node from one document to another.

auto srcDoc = MakeObject<Document>();
auto dstDoc = MakeObject<Document>();
srcDoc->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(MakeObject<Run>(srcDoc, u"Source document first paragraph text."));
dstDoc->get_FirstSection()->get_Body()->get_FirstParagraph()->AppendChild(MakeObject<Run>(dstDoc, u"Destination document first paragraph text."));
// Every node has a parent document, which is the document that contains the node.
// Inserting a node into a document that the node does not belong to will throw an exception.
ASPOSE_ASSERT_NE(dstDoc, srcDoc->get_FirstSection()->get_Document());
ASSERT_THROW(dstDoc->AppendChild(srcDoc->get_FirstSection()), System::ArgumentException);
// Use the ImportNode method to create a copy of a node, which will have the document
// that called the ImportNode method set as its new owner document.
auto importedSection = System::DynamicCast<Section>(dstDoc->ImportNode(srcDoc->get_FirstSection(), true));
ASPOSE_ASSERT_EQ(dstDoc, importedSection->get_Document());
// We can now insert the node into the document.
dstDoc->AppendChild(importedSection);
ASSERT_EQ(u"Destination document first paragraph text.\r\nSource document first paragraph text.\r\n", dstDoc->ToString(SaveFormat::Text));

◆ ImportNode() [2/2]

System::SharedPtr<Aspose::Words::Node> Aspose::Words::DocumentBase::ImportNode ( const 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 and add a character style to each document.
// Configure the styles to have the same name, but different text formatting.
auto srcDoc = MakeObject<Document>();
SharedPtr<Style> srcStyle = srcDoc->get_Styles()->Add(StyleType::Character, u"My style");
srcStyle->get_Font()->set_Name(u"Courier New");
auto srcBuilder = MakeObject<DocumentBuilder>(srcDoc);
srcBuilder->get_Font()->set_Style(srcStyle);
srcBuilder->Writeln(u"Source document text.");
auto dstDoc = MakeObject<Document>();
SharedPtr<Style> dstStyle = dstDoc->get_Styles()->Add(StyleType::Character, u"My style");
dstStyle->get_Font()->set_Name(u"Calibri");
auto dstBuilder = MakeObject<DocumentBuilder>(dstDoc);
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>(dstDoc->ImportNode(srcDoc->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 resolves by adding a suffix.
dstDoc->ImportNode(srcDoc->get_FirstSection(), true, ImportFormatMode::KeepDifferentStyles);
ASSERT_EQ(dstStyle->get_Font()->get_Name(), dstDoc->get_Styles()->idx_get(u"My style")->get_Font()->get_Name());
ASSERT_EQ(srcStyle->get_Font()->get_Name(), dstDoc->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 ( const System::SharedPtr< Aspose::Words::Drawing::Shape > &  value)

◆ set_NodeChangingCallback()

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

◆ set_PageColor()

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

◆ set_ResourceLoadingCallback()

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

◆ set_WarningCallback()

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

◆ Type()

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