Skip to content

Instantly share code, notes, and snippets.

@aspose-words
Last active November 2, 2020 06:28
Show Gist options
  • Save aspose-words/38845012a35610163a07b547a36d6563 to your computer and use it in GitHub Desktop.
Save aspose-words/38845012a35610163a07b547a36d6563 to your computer and use it in GitHub Desktop.
Aspose.Words for C++
This Gist contains code snippets from examples of Aspose.Words for C++.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
System::String supportedDir = dataDir + u"OutSupported";
System::String unknownDir = dataDir + u"OutUnknown";
System::String encryptedDir = dataDir + u"OutEncrypted";
System::String pre97Dir = dataDir + u"OutPre97";
// Create the directories if they do not already exist
if (!System::IO::Directory::Exists(supportedDir))
{
System::IO::Directory::CreateDirectory_(supportedDir);
}
if (!System::IO::Directory::Exists(unknownDir))
{
System::IO::Directory::CreateDirectory_(unknownDir);
}
if (!System::IO::Directory::Exists(encryptedDir))
{
System::IO::Directory::CreateDirectory_(encryptedDir);
}
if (!System::IO::Directory::Exists(pre97Dir))
{
System::IO::Directory::CreateDirectory_(pre97Dir);
}
auto fileList = System::IO::Directory::GetFiles(dataDir);
// Loop through all found files.
for (const auto& fileName: fileList->data())
{
// Extract and display the file name without the path.
System::String nameOnly = System::IO::Path::GetFileName(fileName);
std::cout << nameOnly.ToUtf8String();
// Check the file format and move the file to the appropriate folder.
auto info = FileFormatUtil::DetectFileFormat(fileName);
// Display the document type.
switch (info->get_LoadFormat())
{
case LoadFormat::Doc:
std::cout << "\tMicrosoft Word 97-2003 document." << std::endl;
break;
case LoadFormat::Dot:
std::cout << "\tMicrosoft Word 97-2003 template." << std::endl;
break;
case LoadFormat::Docx:
std::cout << "\tOffice Open XML WordprocessingML Macro-Free Document." << std::endl;
break;
case LoadFormat::Docm:
std::cout << "\tOffice Open XML WordprocessingML Macro-Enabled Document." << std::endl;
break;
case LoadFormat::Dotx:
std::cout << "\tOffice Open XML WordprocessingML Macro-Free Template." << std::endl;
break;
case LoadFormat::Dotm:
std::cout << "\tOffice Open XML WordprocessingML Macro-Enabled Template." << std::endl;
break;
case LoadFormat::FlatOpc:
std::cout << "\tFlat OPC document." << std::endl;
break;
case LoadFormat::Rtf:
std::cout << "\tRTF format." << std::endl;
break;
case LoadFormat::WordML:
std::cout << "\tMicrosoft Word 2003 WordprocessingML format." << std::endl;
break;
case LoadFormat::Html:
std::cout << "\tHTML format." << std::endl;
break;
case LoadFormat::Mhtml:
std::cout << "\tMHTML (Web archive) format." << std::endl;
break;
case LoadFormat::Odt:
std::cout << "\tOpenDocument Text." << std::endl;
break;
case LoadFormat::Ott:
std::cout << "\tOpenDocument Text Template." << std::endl;
break;
case LoadFormat::DocPreWord60:
std::cout << "\tMS Word 6 or Word 95 format." << std::endl;
break;
case LoadFormat::Unknown:
default:
std::cout << "\tUnknown format." << std::endl;
break;
}
// Now copy the document into the appropriate folder.
if (info->get_IsEncrypted())
{
std::cout << "\tAn encrypted document." << std::endl;
System::IO::File::Copy(fileName, System::IO::Path::Combine(encryptedDir, nameOnly), true);
}
else
{
switch (info->get_LoadFormat())
{
case LoadFormat::DocPreWord60:
System::IO::File::Copy(fileName, System::IO::Path::Combine(pre97Dir, nameOnly), true);
break;
case LoadFormat::Unknown:
System::IO::File::Copy(fileName, System::IO::Path::Combine(unknownDir, nameOnly), true);
break;
default:
System::IO::File::Copy(fileName, System::IO::Path::Combine(supportedDir, nameOnly), true);
break;
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Check the file format and move the file to the appropriate folder.
auto info = FileFormatUtil::DetectFileFormat(fileName);
// Display the document type.
switch (info->get_LoadFormat())
{
case LoadFormat::Doc:
std::cout << "\tMicrosoft Word 97-2003 document." << std::endl;
break;
case LoadFormat::Dot:
std::cout << "\tMicrosoft Word 97-2003 template." << std::endl;
break;
case LoadFormat::Docx:
std::cout << "\tOffice Open XML WordprocessingML Macro-Free Document." << std::endl;
break;
case LoadFormat::Docm:
std::cout << "\tOffice Open XML WordprocessingML Macro-Enabled Document." << std::endl;
break;
case LoadFormat::Dotx:
std::cout << "\tOffice Open XML WordprocessingML Macro-Free Template." << std::endl;
break;
case LoadFormat::Dotm:
std::cout << "\tOffice Open XML WordprocessingML Macro-Enabled Template." << std::endl;
break;
case LoadFormat::FlatOpc:
std::cout << "\tFlat OPC document." << std::endl;
break;
case LoadFormat::Rtf:
std::cout << "\tRTF format." << std::endl;
break;
case LoadFormat::WordML:
std::cout << "\tMicrosoft Word 2003 WordprocessingML format." << std::endl;
break;
case LoadFormat::Html:
std::cout << "\tHTML format." << std::endl;
break;
case LoadFormat::Mhtml:
std::cout << "\tMHTML (Web archive) format." << std::endl;
break;
case LoadFormat::Odt:
std::cout << "\tOpenDocument Text." << std::endl;
break;
case LoadFormat::Ott:
std::cout << "\tOpenDocument Text Template." << std::endl;
break;
case LoadFormat::DocPreWord60:
std::cout << "\tMS Word 6 or Word 95 format." << std::endl;
break;
case LoadFormat::Unknown:
default:
std::cout << "\tUnknown format." << std::endl;
break;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto fileList = System::IO::Directory::GetFiles(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Test File (doc).doc");
// Create a new memory stream.
System::SharedPtr<System::IO::MemoryStream> outStream = System::MakeObject<System::IO::MemoryStream>();
// Save the document to stream.
doc->Save(outStream, SaveFormat::Doc);
// Convert the document to byte form.
System::ArrayPtr<uint8_t> docBytes = outStream->ToArray();
// The bytes are now ready to be stored/transmitted.
// Now reverse the steps to load the bytes back into a document object.
System::SharedPtr<System::IO::MemoryStream> inStream = System::MakeObject<System::IO::MemoryStream>(docBytes);
// Load the stream into a new document object.
System::SharedPtr<Document> loadDoc = System::MakeObject<Document>(inStream);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// Initialize a Document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Use a document builder to add content to the document.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello World!");
System::String outputPath = dataDir + GetOutputFilePath(u"CreateDocument.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// The path to the document which is to be processed.
System::String filePath = dataDir + u"Document.Signed.docx";
System::SharedPtr<FileFormatInfo> info = FileFormatUtil::DetectFileFormat(filePath);
if (info->get_HasDigitalSignature())
{
std::cout << "Document " << System::IO::Path::GetFileName(filePath).ToUtf8String() << " has digital signatures, they will be lost if you open/save this document with Aspose.Words." << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<LoadOptions> options = System::MakeObject<LoadOptions>();
options->set_AnnotationsAtBlockLevel(true);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"AnnotationsAtBlockLevel.docx", options);
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<StructuredDocumentTag> sdt = System::DynamicCast<StructuredDocumentTag>(doc->GetChildNodes(NodeType::StructuredDocumentTag, true)->idx_get(0));
System::SharedPtr<BookmarkStart> start = builder->StartBookmark(u"bm");
System::SharedPtr<BookmarkEnd> end = builder->EndBookmark(u"bm");
sdt->get_ParentNode()->InsertBefore(start, sdt);
sdt->get_ParentNode()->InsertAfter(end, sdt);
System::String outputPath = dataDir + GetOutputFilePath(u"Load_Options.AnnotationsAtBlockLevel.docx");
//Save the document into DOCX
doc->Save(outputPath, SaveFormat::Docx);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<LoadOptions> lo = System::MakeObject<LoadOptions>();
//Update the fields with the dirty attribute
lo->set_UpdateDirtyFields(true);
//Load the Word document
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"input.docx", lo);
System::String outputPath = dataDir + GetOutputFilePath(u"Load_Options.LoadOptionsUpdateDirtyFields.docx");
//Save the document into DOCX
doc->Save(outputPath, SaveFormat::Docx);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// Load the document from the absolute path on disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::String outputPath = dataDir + GetOutputFilePath(u"LoadAndSaveToDisk.doc");
// Save the document as DOC document.");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// Load the document from the absolute path on disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// Open the stream. Read only access is enough for Aspose.Words to load a document.
System::SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(dataDir + u"Document.doc");
// Load the entire document into memory.
System::SharedPtr<Document> doc = System::MakeObject<Document>(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream->Close();
// ... do something with the document
// Convert the document to a different format and save to stream.
System::SharedPtr<System::IO::MemoryStream> dstStream = System::MakeObject<System::IO::MemoryStream>();
doc->Save(dstStream, SaveFormat::Doc);
// Rewind the stream position back to zero so it is ready for the next reader.
dstStream->set_Position(0);
// Save the document from stream, to disk. Normally you would do something with the stream directly,
// For example writing the data to a database.
System::String outputPath = dataDir + GetOutputFilePath(u"LoadAndSaveToStream.doc");
System::IO::File::WriteAllBytes(outputPath, dstStream->ToArray());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// Open the stream. Read only access is enough for Aspose.Words to load a document.
System::SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(dataDir + u"Document.doc");
// Load the entire document into memory.
System::SharedPtr<Document> doc = System::MakeObject<Document>(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream->Close();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// The encoding of the text file is automatically detected.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"LoadTxt.txt");
// Save as any Aspose.Words supported format, such as DOCX.
System::String outputPath = dataDir + GetOutputFilePath(u"LoadTxt.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<RtfLoadOptions> loadOptions = System::MakeObject<RtfLoadOptions>();
loadOptions->set_RecognizeUtf8Text(true);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Utf8Text.rtf", loadOptions);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithRTF.rtf");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Input.docx");
System::SharedPtr<TxtSaveOptions> saveOptions = System::MakeObject<TxtSaveOptions>();
saveOptions->set_AddBidiMarks(false);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingwithTxt.AddBidiMarks.txt");
doc->Save(outputPath, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<TxtLoadOptions> loadOptions = System::MakeObject<TxtLoadOptions>();
loadOptions->set_DetectNumberingWithWhitespaces(false);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"LoadTxt.txt", loadOptions);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingwithTxt.DetectNumberingWithWhitespaces.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<TxtLoadOptions> loadOptions = System::MakeObject<TxtLoadOptions>();
loadOptions->set_LeadingSpacesOptions(TxtLeadingSpacesOptions::Trim);
loadOptions->set_TrailingSpacesOptions(TxtTrailingSpacesOptions::Trim);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"LoadTxt.txt", loadOptions);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingwithTxt.HandleSpacesOptions.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingwithTxt.SaveAsTxt.txt");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directory.
System::String dataDir = GetDataDir_MailMergeAndReporting();
// Open an existing document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"MailMerge.ExecuteArray.doc");
// Trim trailing and leading whitespaces mail merge values
doc->get_MailMerge()->set_TrimWhitespaces(false);
// Fill the fields in the document with user data.
System::ArrayPtr<System::String> names = System::MakeArray<System::String>({u"FullName", u"Company", u"Address", u"Address2", u"City"});
System::ArrayPtr<TObjectPtr> values = System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::String>(u"James Bond"),
System::ObjectExt::Box<System::String>(u"MI5 Headquarters"),
System::ObjectExt::Box<System::String>(u"Milbank"),
System::ObjectExt::Box<System::String>(u""),
System::ObjectExt::Box<System::String>(u"London")});
doc->get_MailMerge()->Execute(names, values);
System::String outputPath = dataDir + GetOutputFilePath(u"ExecuteArray.doc");
// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
class MailMergeSwitches : public IFieldMergingCallback
{
typedef MailMergeSwitches ThisType;
typedef IFieldMergingCallback BaseType;
typedef System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
public:
void FieldMerging(System::SharedPtr<FieldMergingArgs> e) override;
void ImageFieldMerging(System::SharedPtr<ImageFieldMergingArgs> args) override {}
};
RTTI_INFO_IMPL_HASH(273698781u, MailMergeSwitches, ThisTypeBaseTypesInfo);
void MailMergeSwitches::FieldMerging(System::SharedPtr<FieldMergingArgs> e)
{
if (e->get_FieldName().StartsWith(u"HTML"))
{
if (e->get_Field()->GetFieldCode().Contains(u"\\b"))
{
System::SharedPtr<FieldMergeField> field = e->get_Field();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(e->get_Document());
builder->MoveToMergeField(e->get_DocumentFieldName(), true, false);
builder->Write(field->get_TextBefore());
builder->Write(System::ObjectExt::ToString(e->get_FieldValue()));
e->set_Text(u"");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directory.
System::String dataDir = GetDataDir_MailMergeAndReporting();
// Open an existing document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"UnconditionalMergeFieldsAndRegions.docx");
//Merge fields and merge regions are merged regardless of the parent IF field's condition.
doc->get_MailMerge()->set_UnconditionalMergeFieldsAndRegions(true);
// Fill the fields in the document with user data.
doc->get_MailMerge()->Execute(System::MakeArray<System::String>({u"FullName"}), System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::String>(u"James Bond")}));
System::String outputPath = dataDir + GetOutputFilePath(u"MailMergeAndConditionalField.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
class HandleMergeField : public IFieldMergingCallback
{
typedef HandleMergeField ThisType;
typedef IFieldMergingCallback BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
public:
void FieldMerging(System::SharedPtr<FieldMergingArgs> e) override;
void ImageFieldMerging(System::SharedPtr<ImageFieldMergingArgs> args) override {}
protected:
System::Object::shared_members_type GetSharedMembers() override;
private:
System::SharedPtr<DocumentBuilder> mBuilder;
};
RTTI_INFO_IMPL_HASH(1055131746u, HandleMergeField, ThisTypeBaseTypesInfo);
void HandleMergeField::FieldMerging(System::SharedPtr<FieldMergingArgs> e)
{
if (mBuilder == nullptr)
{
mBuilder = System::MakeObject<DocumentBuilder>(e->get_Document());
}
// We decided that we want all boolean values to be output as check box form fields.
if (System::ObjectExt::Is<bool>(e->get_FieldValue()))
{
// Move the "cursor" to the current merge field.
mBuilder->MoveToMergeField(e->get_FieldName());
// It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
System::String checkBoxName = System::String::Format(u"{0}{1}",e->get_FieldName(),e->get_RecordIndex());
// Insert a check box.
mBuilder->InsertCheckBox(checkBoxName, System::ObjectExt::Unbox<bool>(e->get_FieldValue()), 0);
// Nothing else to do for this field.
return;
}
// We want to insert html during mail merge.
if (e->get_FieldName() == u"Body")
{
mBuilder->MoveToMergeField(e->get_FieldName());
mBuilder->Write(System::ObjectExt::Unbox<System::String>(e->get_FieldValue()));
}
// Another example, we want the Subject field to come out as text input form field.
if (e->get_FieldName() == u"Subject")
{
mBuilder->MoveToMergeField(e->get_FieldName());
System::String textInputName = System::String::Format(u"{0}{1}",e->get_FieldName(),e->get_RecordIndex());
mBuilder->InsertTextInput(textInputName, TextFormFieldType::Regular, u"", System::ObjectExt::Unbox<System::String>(e->get_FieldValue()), 0);
}
}
System::Object::shared_members_type HandleMergeField::GetSharedMembers()
{
auto result = System::Object::GetSharedMembers();
result.Add("HandleMergeField::mBuilder", this->mBuilder);
return result;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directory.
System::String dataDir = GetDataDir_MailMergeAndReporting();
//System::String fileName = u"Template.doc";
// Load the template document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Template.doc");
// Setup mail merge event handler to do the custom work.
doc->get_MailMerge()->set_FieldMergingCallback(System::MakeObject<HandleMergeField>());
// Trim trailing and leading whitespaces mail merge values
doc->get_MailMerge()->set_TrimWhitespaces(false);
// This is the data for mail merge.
System::ArrayPtr<System::String> names = System::MakeArray<System::String>({u"RecipientName", u"SenderName", u"FaxNumber", u"PhoneNumber", u"Subject", u"Body", u"Urgent", u"ForReview", u"PleaseComment"});
System::ArrayPtr<TObjectPtr> values = System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::String>(u"Josh"),
System::ObjectExt::Box<System::String>(u"Jenny"),
System::ObjectExt::Box<System::String>(u"123456789"),
System::ObjectExt::Box<System::String>(u""),
System::ObjectExt::Box<System::String>(u"Hello"),
System::ObjectExt::Box<System::String>(u"<b>HTML Body Test message 1</b>"),
System::ObjectExt::Box<bool>(true),
System::ObjectExt::Box<bool>(false),
System::ObjectExt::Box<bool>(true)});
// Execute the mail merge.
doc->get_MailMerge()->Execute(names, values);
System::String outputPath = dataDir + GetOutputFilePath(u"MailMergeFormFields.doc");
// Save the finished document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<IMailMergeDataSource> CustomerMailMergeDataSource::GetChildDataSource(System::String tableName)
{
const System::String& switch_value_1 = tableName;
if (tableName == u"Order")
{
return System::MakeObject<OrderMailMergeDataSource>(mCustomers->idx_get(mRecordIndex)->GetOrders());
}
else
{
return nullptr;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_MailMergeAndReporting();
// Create some data that we will use in the mail merge.
TCustomerIListPtr customers = System::MakeObject<TCustomerList>();
customers->Add(System::MakeObject<Customer>(u"Thomas Hardy", u"120 Hanover Sq., London"));
customers->Add(System::MakeObject<Customer>(u"Paolo Accorti", u"Via Monte Bianco 34, Torino"));
// Create some data for nesting in the mail merge.
customers->idx_get(0)->GetOrders()->Add(System::MakeObject<Order>(u"Rugby World Cup Cap", 2));
customers->idx_get(0)->GetOrders()->Add(System::MakeObject<Order>(u"Rugby World Cup Ball", 1));
customers->idx_get(1)->GetOrders()->Add(System::MakeObject<Order>(u"Rugby World Cup Guide", 1));
// Open the template document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"NestedMailMerge.CustomDataSource.doc");
// To be able to mail merge from your own data source, it must be wrapped
// Into an object that implements the IMailMergeDataSource interface.
System::SharedPtr<CustomerMailMergeDataSource> customersDataSource = System::MakeObject<CustomerMailMergeDataSource>(customers);
// Now you can pass your data source into Aspose.Words.
doc->get_MailMerge()->ExecuteWithRegions(customersDataSource);
System::String outputPath = dataDir + GetOutputFilePath(u"NestedMailMergeCustom.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directory.
System::String dataDir = GetDataDir_MailMergeAndReporting();
// Open an existing document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"MailMerge.ExecuteArray.doc");
doc->get_MailMerge()->set_UseNonMergeFields(true);
// Fill the fields in the document with user data.
System::ArrayPtr<System::String> names = System::MakeArray<System::String>({u"FullName", u"Company", u"Address", u"Address2", u"City"});
System::ArrayPtr<TObjectPtr> values = System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::String>(u"James Bond"),
System::ObjectExt::Box<System::String>(u"MI5 Headquarters"),
System::ObjectExt::Box<System::String>(u"Milbank"),
System::ObjectExt::Box<System::String>(u""),
System::ObjectExt::Box<System::String>(u"London")});
doc->get_MailMerge()->Execute(names, values);
System::String outputPath = dataDir + GetOutputFilePath(u"SimpleMailMerge.doc");
// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Bookmarks.doc");
// By index.
System::SharedPtr<Bookmark> bookmark1 = doc->get_Range()->get_Bookmarks()->idx_get(0);
// By name.
System::SharedPtr<Bookmark> bookmark2 = doc->get_Range()->get_Bookmarks()->idx_get(u"Bookmark2");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
System::SharedPtr<Bookmark> bookmark = doc->get_Range()->get_Bookmarks()->idx_get(u"MyBookmark");
// Get the name and text of the bookmark.
System::String name = bookmark->get_Name();
System::String text = bookmark->get_Text();
// Set the name and text of the bookmark.
bookmark->set_Name(u"RenamedBookmark");
bookmark->set_Text(u"This is a new bookmarked text.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithBookmarks();
// Create empty document
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Table> table = builder->StartTable();
// Insert a cell
builder->InsertCell();
// Start bookmark here after calling InsertCell
builder->StartBookmark(u"MyBookmark");
builder->Write(u"This is row 1 cell 1");
// Insert a cell
builder->InsertCell();
builder->Write(u"This is row 1 cell 2");
builder->EndRow();
// Insert a cell
builder->InsertCell();
builder->Writeln(u"This is row 2 cell 1");
// Insert a cell
builder->InsertCell();
builder->Writeln(u"This is row 2 cell 2");
builder->EndRow();
builder->EndTable();
// End of bookmark
builder->EndBookmark(u"MyBookmark");
System::String outputPath = dataDir + GetOutputFilePath(u"BookmarkTable.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->StartBookmark(u"My Bookmark");
builder->Writeln(u"Text inside a bookmark.");
builder->StartBookmark(u"Nested Bookmark");
builder->Writeln(u"Text inside a NestedBookmark.");
builder->EndBookmark(u"Nested Bookmark");
builder->Writeln(u"Text after Nested Bookmark.");
builder->EndBookmark(u"My Bookmark");
System::SharedPtr<DocSaveOptions> options = System::MakeObject<DocSaveOptions>();
System::String outputPath = dataDir + GetOutputFilePath(u"CreateBookmark.doc");
doc->Save(outputPath, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithComments();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Write(u"Some text is added.");
System::SharedPtr<Comment> comment = System::MakeObject<Comment>(doc, u"Awais Hafeez", u"AH", System::DateTime::get_Today());
builder->get_CurrentParagraph()->AppendChild(comment);
comment->get_Paragraphs()->Add(System::MakeObject<Paragraph>(doc));
comment->get_FirstParagraph()->get_Runs()->Add(System::MakeObject<Run>(doc, u"Comment text."));
System::String outputPath = dataDir + GetOutputFilePath(u"AddComments.doc");
// Save the document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Write(u"Some text is added.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithComments();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<Paragraph> para1 = System::MakeObject<Paragraph>(doc);
System::SharedPtr<Run> run1 = System::MakeObject<Run>(doc, u"Some ");
System::SharedPtr<Run> run2 = System::MakeObject<Run>(doc, u"text ");
para1->AppendChild(run1);
para1->AppendChild(run2);
doc->get_FirstSection()->get_Body()->AppendChild(para1);
System::SharedPtr<Paragraph> para2 = System::MakeObject<Paragraph>(doc);
System::SharedPtr<Run> run3 = System::MakeObject<Run>(doc, u"is ");
System::SharedPtr<Run> run4 = System::MakeObject<Run>(doc, u"added ");
para2->AppendChild(run3);
para2->AppendChild(run4);
doc->get_FirstSection()->get_Body()->AppendChild(para2);
System::SharedPtr<Comment> comment = System::MakeObject<Comment>(doc, u"Awais Hafeez", u"AH", System::DateTime::get_Today());
comment->get_Paragraphs()->Add(System::MakeObject<Paragraph>(doc));
comment->get_FirstParagraph()->get_Runs()->Add(System::MakeObject<Run>(doc, u"Comment text."));
System::SharedPtr<CommentRangeStart> commentRangeStart = System::MakeObject<CommentRangeStart>(doc, comment->get_Id());
System::SharedPtr<CommentRangeEnd> commentRangeEnd = System::MakeObject<CommentRangeEnd>(doc, comment->get_Id());
run1->get_ParentNode()->InsertAfter(commentRangeStart, run1);
run3->get_ParentNode()->InsertAfter(commentRangeEnd, run3);
commentRangeEnd->get_ParentNode()->InsertAfter(comment, commentRangeEnd);
System::String outputPath = dataDir + GetOutputFilePath(u"AnchorComment.doc");
// Save the document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithComments();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
System::SharedPtr<Comment> comment = System::DynamicCast<Comment>(doc->GetChild(NodeType::Comment, 0, true));
//Remove the reply
comment->RemoveReply(comment->get_Replies()->idx_get(0));
//Add a reply to comment
comment->AddReply(u"John Doe", u"JD", System::DateTime(2017, 9, 25, 12, 15, 0), u"New reply");
System::String outputPath = dataDir + GetOutputFilePath(u"CommentReply.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void CommentResolvedandReplies(const System::SharedPtr<Document>& doc)
{
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
System::SharedPtr<Comment> parentComment = System::DynamicCast<Comment>(comments->idx_get(0));
for (System::SharedPtr<Comment> childComment : System::IterateOver<System::SharedPtr<Comment>>(parentComment->get_Replies()))
{
// Get comment parent and status.
std::cout << childComment->get_Ancestor()->get_Id() << std::endl << childComment->get_Done() << std::endl;
// And update comment Done mark.
childComment->set_Done(true);
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::String> ExtractComments(const System::SharedPtr<Document>& doc)
{
std::vector<System::String> collectedComments;
// Collect all comments in the document
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// Look through all comments and gather information about them.
for (System::SharedPtr<Comment> comment : System::IterateOver<System::SharedPtr<Comment>>(comments))
{
collectedComments.push_back(comment->get_Author() + u" " + comment->get_DateTime() + u" " + System::StaticCast<Node>(comment)->ToString(SaveFormat::Text));
}
return collectedComments;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::String> ExtractComments(const System::SharedPtr<Document>& doc, const System::String& authorName)
{
std::vector<System::String> collectedComments;
// Collect all comments in the document
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// Look through all comments and gather information about those written by the authorName author.
for (System::SharedPtr<Comment> comment : System::IterateOver<System::SharedPtr<Comment>>(comments))
{
if (comment->get_Author() == authorName)
{
collectedComments.push_back(comment->get_Author() + u" " + comment->get_DateTime() + u" " + System::StaticCast<Node>(comment)->ToString(SaveFormat::Text));
}
}
return collectedComments;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithComments();
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Extract the information about the comments of all the authors.
for (auto& comment : ExtractComments(doc))
{
std::cout << comment.ToUtf8String();
}
// Remove comments by the "pm" author.
RemoveComments(doc, u"pm");
std::cout << "Comments from \"pm\" are removed!" << std::endl;
// Extract the information about the comments of the "ks" author.
for (auto& comment: ExtractComments(doc, u"ks"))
{
std::cout << comment.ToUtf8String();
}
//Read the comment's reply and resolve them.
CommentResolvedandReplies(doc);
// Remove all comments.
RemoveComments(doc);
std::cout << "All comments are removed!" << std::endl;
System::String outputPath = dataDir + GetOutputFilePath(u"ProcessComments.doc");
// Save the document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void RemoveComments(const System::SharedPtr<Document>& doc)
{
// Collect all comments in the document
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// Remove all comments.
comments->Clear();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void RemoveComments(const System::SharedPtr<Document>& doc, const System::String& authorName)
{
// Collect all comments in the document
System::SharedPtr<NodeCollection> comments = doc->GetChildNodes(NodeType::Comment, true);
// Look through all comments and remove those written by the authorName author.
for (int32_t i = comments->get_Count() - 1; i >= 0; i--)
{
System::SharedPtr<Comment> comment = System::DynamicCast<Comment>(comments->idx_get(i));
if (comment->get_Author() == authorName)
{
comment->Remove();
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<PageSetup> pageSetup = builder->get_PageSetup();
pageSetup->set_TopMargin(ConvertUtil::InchToPoint(1.0));
pageSetup->set_BottomMargin(ConvertUtil::InchToPoint(1.0));
pageSetup->set_LeftMargin(ConvertUtil::InchToPoint(1.5));
pageSetup->set_RightMargin(ConvertUtil::InchToPoint(1.5));
pageSetup->set_HeaderDistance(ConvertUtil::InchToPoint(0.2));
pageSetup->set_FooterDistance(ConvertUtil::InchToPoint(0.2));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::String text = u"test\r";
// Replace "\r" control character with "\r\n"
text = text.Replace(ControlChar::Cr(), ControlChar::CrLf());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Load the template document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Get styles collection from document.
System::SharedPtr<StyleCollection> styles = doc->get_Styles();
System::String styleName = u"";
// Iterate through all the styles.
for (System::SharedPtr<Style> style : System::IterateOver(styles))
{
if (styleName == u"")
{
styleName = style->get_Name();
}
else
{
styleName = styleName + u", " + style->get_Name();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
doc->EnsureMinimum();
System::SharedPtr<GroupShape> gs = System::MakeObject<GroupShape>(doc);
System::SharedPtr<Shape> shape = System::MakeObject<Shape>(doc, ShapeType::AccentBorderCallout1);
shape->set_Width(100);
shape->set_Height(100);
gs->AppendChild(shape);
System::SharedPtr<Shape> shape1 = System::MakeObject<Shape>(doc, ShapeType::ActionButtonBeginning);
shape1->set_Left(100);
shape1->set_Width(100);
shape1->set_Height(200);
gs->AppendChild(shape1);
gs->set_Width(200);
gs->set_Height(200);
gs->set_CoordSize(System::Drawing::Size(200, 200));
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertNode(gs);
System::String outputPath = dataDir + GetOutputFilePath(u"AddGroupShapeToDocument.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Open the empty document
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<StructuredDocumentTag> SdtCheckBox = System::MakeObject<StructuredDocumentTag>(doc, SdtType::Checkbox, MarkupLevel::Inline);
// Insert content control into the document
builder->InsertNode(SdtCheckBox);
System::String outputPath = dataDir + GetOutputFilePath(u"CheckBoxTypeContentControl.docx");
doc->Save(outputPath, SaveFormat::Docx);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::SharedPtr<CleanupOptions> cleanupoptions = System::MakeObject<CleanupOptions>();
cleanupoptions->set_UnusedLists(false);
cleanupoptions->set_UnusedStyles(true);
// Cleans unused styles and lists from the document depending on given CleanupOptions.
doc->Cleanup(cleanupoptions);
System::String outputPath = dataDir + GetOutputFilePath(u"CleansUnusedStylesandLists.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
System::SharedPtr<Document> clone = doc->Clone();
System::String outputPath = dataDir + GetOutputFilePath(u"CloningDocument.doc");
// Save the document to disk.
clone->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<StructuredDocumentTag> sdt = System::MakeObject<StructuredDocumentTag>(doc, SdtType::ComboBox, MarkupLevel::Block);
sdt->get_ListItems()->Add(System::MakeObject<SdtListItem>(u"Choose an item", u"-1"));
sdt->get_ListItems()->Add(System::MakeObject<SdtListItem>(u"Item 1", u"1"));
sdt->get_ListItems()->Add(System::MakeObject<SdtListItem>(u"Item 2", u"2"));
doc->get_FirstSection()->get_Body()->AppendChild(sdt);
System::String outputPath = dataDir + GetOutputFilePath(u"ComboBoxContentControl.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::SharedPtr<Node>> ExtractContent(System::SharedPtr<Node> startNode, System::SharedPtr<Node> endNode, bool isInclusive)
{
// First check that the nodes passed to this method are valid for use.
VerifyParameterNodes(startNode, endNode);
// Create a list to store the extracted nodes.
std::vector<System::SharedPtr<Node>> nodes;
// Keep a record of the original nodes passed to this method so we can split marker nodes if needed.
System::SharedPtr<Node> originalStartNode = startNode;
System::SharedPtr<Node> originalEndNode = endNode;
// Extract content based on block level nodes (paragraphs and tables). Traverse through parent nodes to find them.
// We will split the content of first and last nodes depending if the marker nodes are inline
while (startNode->get_ParentNode()->get_NodeType() != NodeType::Body)
{
startNode = startNode->get_ParentNode();
}
while (endNode->get_ParentNode()->get_NodeType() != NodeType::Body)
{
endNode = endNode->get_ParentNode();
}
bool isExtracting = true;
bool isStartingNode = true;
bool isEndingNode = false;
// The current node we are extracting from the document.
System::SharedPtr<Node> currNode = startNode;
// Begin extracting content. Process all block level nodes and specifically split the first and last nodes when needed so paragraph formatting is retained.
// Method is little more complex than a regular extractor as we need to factor in extracting using inline nodes, fields, bookmarks etc as to make it really useful.
while (isExtracting)
{
// Clone the current node and its children to obtain a copy.
System::SharedPtr<Node> cloneNode = currNode->Clone(true);
isEndingNode = System::ObjectExt::Equals(currNode, endNode);
if ((isStartingNode || isEndingNode) && cloneNode->get_IsComposite())
{
// We need to process each marker separately so pass it off to a separate method instead.
if (isStartingNode)
{
ProcessMarker(System::DynamicCast<CompositeNode>(cloneNode), nodes, originalStartNode, isInclusive, isStartingNode, isEndingNode);
isStartingNode = false;
}
// Conditional needs to be separate as the block level start and end markers maybe the same node.
if (isEndingNode)
{
ProcessMarker(System::DynamicCast<CompositeNode>(cloneNode), nodes, originalEndNode, isInclusive, isStartingNode, isEndingNode);
isExtracting = false;
}
}
else
{
nodes.push_back(cloneNode);
}
// Move to the next node and extract it. If next node is null that means the rest of the content is found in a different section.
if (currNode->get_NextSibling() == nullptr && isExtracting)
{
// Move to the next section.
System::SharedPtr<Section> nextSection = System::DynamicCast<Section>(currNode->GetAncestor(NodeType::Section)->get_NextSibling());
currNode = nextSection->get_Body()->get_FirstChild();
}
else
{
// Move to the next node in the body.
currNode = currNode->get_NextSibling();
}
}
// Return the nodes between the node markers.
return nodes;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void VerifyParameterNodes(const System::SharedPtr<Node>& startNode, const System::SharedPtr<Node>& endNode)
{
// The order in which these checks are done is important.
if (startNode == nullptr)
{
throw System::ArgumentException(u"Start node cannot be null");
}
if (endNode == nullptr)
{
throw System::ArgumentException(u"End node cannot be null");
}
if (!System::ObjectExt::Equals(startNode->get_Document(), endNode->get_Document()))
{
throw System::ArgumentException(u"Start node and end node must belong to the same document");
}
if (startNode->GetAncestor(NodeType::Body) == nullptr || endNode->GetAncestor(NodeType::Body) == nullptr)
{
throw System::ArgumentException(u"Start node and end node must be a child or descendant of a body");
}
// Check the end node is after the start node in the DOM tree
// First check if they are in different sections, then if they're not check their position in the body of the same section they are in.
System::SharedPtr<Section> startSection = System::DynamicCast<Section>(startNode->GetAncestor(NodeType::Section));
System::SharedPtr<Section> endSection = System::DynamicCast<Section>(endNode->GetAncestor(NodeType::Section));
int32_t startIndex = startSection->get_ParentNode()->IndexOf(startSection);
int32_t endIndex = endSection->get_ParentNode()->IndexOf(endSection);
if (startIndex == endIndex)
{
if (startSection->get_Body()->IndexOf(startNode) > endSection->get_Body()->IndexOf(endNode))
{
throw System::ArgumentException(u"The end node must be after the start node in the body");
}
}
else if (startIndex > endIndex)
{
throw System::ArgumentException(u"The section of end node must be after the section start node");
}
}
bool IsInline(const System::SharedPtr<Node>& node)
{
// Test if the node is desendant of a Paragraph or Table node and also is not a paragraph or a table a paragraph inside a comment class which is decesant of a pararaph is possible.
return ((node->GetAncestor(NodeType::Paragraph) != nullptr || node->GetAncestor(NodeType::Table) != nullptr)
&& !(node->get_NodeType() == NodeType::Paragraph || node->get_NodeType() == NodeType::Table));
}
void ProcessMarker(const System::SharedPtr<CompositeNode>& cloneNode, std::vector<System::SharedPtr<Node>>& nodes, System::SharedPtr<Node> node, bool isInclusive, bool isStartMarker, bool isEndMarker)
{
// If we are dealing with a block level node just see if it should be included and add it to the list.
if (!IsInline(node))
{
// Don't add the node twice if the markers are the same node
if (!(isStartMarker && isEndMarker))
{
if (isInclusive)
{
nodes.push_back(cloneNode);
}
}
return;
}
// If a marker is a FieldStart node check if it's to be included or not.
// We assume for simplicity that the FieldStart and FieldEnd appear in the same paragraph.
if (node->get_NodeType() == NodeType::FieldStart)
{
// If the marker is a start node and is not be included then skip to the end of the field.
// If the marker is an end node and it is to be included then move to the end field so the field will not be removed.
if ((isStartMarker && !isInclusive) || (!isStartMarker && isInclusive))
{
while (node->get_NextSibling() != nullptr && node->get_NodeType() != NodeType::FieldEnd)
{
node = node->get_NextSibling();
}
}
}
// If either marker is part of a comment then to include the comment itself we need to move the pointer forward to the Comment
// Node found after the CommentRangeEnd node.
if (node->get_NodeType() == NodeType::CommentRangeEnd)
{
while (node->get_NextSibling() != nullptr && node->get_NodeType() != NodeType::Comment)
{
node = node->get_NextSibling();
}
}
// Find the corresponding node in our cloned node by index and return it.
// If the start and end node are the same some child nodes might already have been removed. Subtract the
// Difference to get the right index.
int32_t indexDiff = node->get_ParentNode()->get_ChildNodes()->get_Count() - cloneNode->get_ChildNodes()->get_Count();
// Child node count identical.
if (indexDiff == 0)
{
node = cloneNode->get_ChildNodes()->idx_get(node->get_ParentNode()->IndexOf(node));
}
else
{
node = cloneNode->get_ChildNodes()->idx_get(node->get_ParentNode()->IndexOf(node) - indexDiff);
}
// Remove the nodes up to/from the marker.
bool isSkip = false;
bool isProcessing = true;
bool isRemoving = isStartMarker;
System::SharedPtr<Node> nextNode = cloneNode->get_FirstChild();
while (isProcessing && nextNode != nullptr)
{
System::SharedPtr<Node> currentNode = nextNode;
isSkip = false;
if (System::ObjectExt::Equals(currentNode, node))
{
if (isStartMarker)
{
isProcessing = false;
if (isInclusive)
{
isRemoving = false;
}
}
else
{
isRemoving = true;
if (isInclusive)
{
isSkip = true;
}
}
}
nextNode = nextNode->get_NextSibling();
if (isRemoving && !isSkip)
{
currentNode->Remove();
}
}
// After processing the composite node may become empty. If it has don't include it.
if (!(isStartMarker && isEndMarker))
{
if (cloneNode->get_HasChildNodes())
{
nodes.push_back(cloneNode);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> GenerateDocument(const System::SharedPtr<Document>& srcDoc, const std::vector<System::SharedPtr<Node>>& nodes)
{
// Create a blank document.
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>();
// Remove the first paragraph from the empty document.
dstDoc->get_FirstSection()->get_Body()->RemoveAllChildren();
// Import each node from the list into the new document. Keep the original formatting of the node.
System::SharedPtr<NodeImporter> importer = System::MakeObject<NodeImporter>(srcDoc, dstDoc, ImportFormatMode::KeepSourceFormatting);
for (auto& node : nodes)
{
System::SharedPtr<Node> importNode = importer->ImportNode(node, true);
dstDoc->get_FirstSection()->get_Body()->AppendChild(importNode);
}
// Return the generated document.
return dstDoc;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Clones and copies headers/footers form the previous section to the specified section.
void CopyHeadersFootersFromPreviousSection(const System::SharedPtr<Section>& section)
{
System::SharedPtr<Section> previousSection = System::DynamicCast<Section>(section->get_PreviousSibling());
if (previousSection == nullptr)
{
return;
}
section->get_HeadersFooters()->Clear();
for (System::SharedPtr<Node> headerFooterNode : System::IterateOver(previousSection->get_HeadersFooters()))
{
section->get_HeadersFooters()->Add(headerFooterNode->Clone(true));
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Section> currentSection = builder->get_CurrentSection();
System::SharedPtr<PageSetup> pageSetup = currentSection->get_PageSetup();
// Specify if we want headers/footers of the first page to be different from other pages.
// You can also use PageSetup.OddAndEvenPagesHeaderFooter property to specify
// Different headers/footers for odd and even pages.
pageSetup->set_DifferentFirstPageHeaderFooter(true);
// --- Create header for the first page. ---
pageSetup->set_HeaderDistance(20);
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
// Set font properties for header text.
builder->get_Font()->set_Name(u"Arial");
builder->get_Font()->set_Bold(true);
builder->get_Font()->set_Size(14);
// Specify header title for the first page.
builder->Write(u"Aspose.Words Header/Footer Creation Primer - Title Page.");
// --- Create header for pages other than first. ---
pageSetup->set_HeaderDistance(20);
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
// Insert absolutely positioned image into the top/left corner of the header.
// Distance from the top/left edges of the page is set to 10 points.
System::String imageFileName = dataDir + u"Aspose.Words.gif";
builder->InsertImage(imageFileName, RelativeHorizontalPosition::Page, 10, RelativeVerticalPosition::Page, 10, 50, 50, WrapType::Through);
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Right);
// Specify another header title for other pages.
builder->Write(u"Aspose.Words Header/Footer Creation Primer.");
// --- Create footer for pages other than first. ---
builder->MoveToHeaderFooter(HeaderFooterType::FooterPrimary);
// We use table with two cells to make one part of the text on the line (with page numbering)
// To be aligned left, and the other part of the text (with copyright) to be aligned right.
builder->StartTable();
// Clear table borders.
builder->get_CellFormat()->ClearFormatting();
builder->InsertCell();
// Set first cell to 1/3 of the page width.
builder->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(100 / 3));
// Insert page numbering text here.
// It uses PAGE and NUMPAGES fields to auto calculate current page number and total number of pages.
builder->Write(u"Page ");
builder->InsertField(u"PAGE", u"");
builder->Write(u" of ");
builder->InsertField(u"NUMPAGES", u"");
// Align this text to the left.
builder->get_CurrentParagraph()->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Left);
builder->InsertCell();
// Set the second cell to 2/3 of the page width.
builder->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(100 * 2 / 3));
builder->Write(u"(C) 2001 Aspose Pty Ltd. All rights reserved.");
// Align this text to the right.
builder->get_CurrentParagraph()->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Right);
builder->EndRow();
builder->EndTable();
builder->MoveToDocumentEnd();
// Make page break to create a second page on which the primary headers/footers will be seen.
builder->InsertBreak(BreakType::PageBreak);
// Make section break to create a third page with different page orientation.
builder->InsertBreak(BreakType::SectionBreakNewPage);
// Get the new section and its page setup.
currentSection = builder->get_CurrentSection();
pageSetup = currentSection->get_PageSetup();
// Set page orientation of the new section to landscape.
pageSetup->set_Orientation(Orientation::Landscape);
// This section does not need different first page header/footer.
// We need only one title page in the document and the header/footer for this page
// Has already been defined in the previous section
pageSetup->set_DifferentFirstPageHeaderFooter(false);
// This section displays headers/footers from the previous section by default.
// Call currentSection.HeadersFooters.LinkToPrevious(false) to cancel this.
// Page width is different for the new section and therefore we need to set
// A different cell widths for a footer table.
currentSection->get_HeadersFooters()->LinkToPrevious(false);
// If we want to use the already existing header/footer set for this section
// But with some minor modifications then it may be expedient to copy headers/footers
// From the previous section and apply the necessary modifications where we want them.
CopyHeadersFootersFromPreviousSection(currentSection);
// Find the footer that we want to change.
System::SharedPtr<HeaderFooter> primaryFooter = currentSection->get_HeadersFooters()->idx_get(HeaderFooterType::FooterPrimary);
System::SharedPtr<Row> row = primaryFooter->get_Tables()->idx_get(0)->get_FirstRow();
row->get_FirstCell()->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(100 / 3));
row->get_LastCell()->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(100 * 2 / 3));
System::String outputPath = dataDir + GetOutputFilePath(u"CreateHeaderFooterUsingDocBuilder.doc");
// Save the resulting document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Properties.doc");
System::SharedPtr<CustomDocumentProperties> props = doc->get_CustomDocumentProperties();
if (props->idx_get(u"Authorized") == nullptr)
{
props->Add(u"Authorized", true);
props->Add(u"Authorized By", System::String(u"John Smith"));
props->Add(u"Authorized Date", System::DateTime::get_Today());
props->Add(u"Authorized Revision", doc->get_BuiltInDocumentProperties()->get_RevisionNumber());
props->Add(u"Authorized Amount", 123.45);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Properties.doc");
doc->get_CustomDocumentProperties()->Remove(u"Authorized Date");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::String fileName = dataDir + u"Properties.doc";
System::SharedPtr<Document> doc = System::MakeObject<Document>(fileName);
std::cout << "1. Document name: " << fileName.ToUtf8String() << std::endl;
std::cout << "2. Built-in Properties" << std::endl;
for (System::SharedPtr<DocumentProperty> prop : System::IterateOver(doc->get_BuiltInDocumentProperties()))
{
std::cout << prop->get_Name().ToUtf8String() << " : " << prop->get_Value()->ToString().ToUtf8String() << std::endl;
}
std::cout << "3. Custom Properties" << std::endl;
for (System::SharedPtr<DocumentProperty> prop : System::IterateOver(doc->get_CustomDocumentProperties()))
{
std::cout << prop->get_Name().ToUtf8String() << " : " << prop->get_Value()->ToString().ToUtf8String() << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Properties.doc");
doc->set_RemovePersonalInformation(true);
System::String outputPath = dataDir + GetOutputFilePath(u"DocProperties.RemovePersonalInformation.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Table> table = builder->StartTable();
// Insert a cell
builder->InsertCell();
// Use fixed column widths.
table->AutoFit(AutoFitBehavior::FixedColumnWidths);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"This is row 1 cell 1");
// Insert a cell
builder->InsertCell();
builder->Write(u"This is row 1 cell 2");
builder->EndRow();
// Insert a cell
builder->InsertCell();
// Apply new row formatting
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Writeln(u"This is row 2 cell 1");
// Insert a cell
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Writeln(u"This is row 2 cell 2");
builder->EndRow();
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderBuildTable.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->StartBookmark(u"FineBookmark");
builder->Writeln(u"This is just a fine bookmark.");
builder->EndBookmark(u"FineBookmark");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertBookmark.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"This is page 1.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"This is page 2.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"This is page 3.");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertBreak.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertCheckBox(u"CheckBox", true, true, 0);
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertElements.InsertCheckBoxFormField.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::ArrayPtr<System::String> items = System::MakeArray<System::String>({u"One", u"Two", u"Three"});
builder->InsertComboBox(u"DropDown", items, 0);
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertElements.InsertComboBoxFormField.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertOleObject(u"http://www.aspose.com", u"htmlfile", true, true, nullptr);
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertElements.InsertOleObject.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a table of contents at the beginning of the document.
builder->InsertTableOfContents(u"\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder->InsertBreak(BreakType::PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
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::Heading2);
builder->Writeln(u"Heading 3.2");
builder->Writeln(u"Heading 3.3");
doc->UpdateFields();
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertElements.InsertTableOfContents.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertTextInput(u"TextInput", TextFormFieldType::Regular, u"", u"Hello", 0);
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertElements.InsertTextInputFormField.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::ArrayPtr<uint8_t> bs = System::IO::File::ReadAllBytes(dataDir + u"input.zip");
System::SharedPtr<System::IO::Stream> stream = System::MakeObject<System::IO::MemoryStream>(bs);
System::SharedPtr<Shape> shape = builder->InsertOleObject(stream, u"Package", true, nullptr);
System::SharedPtr<OlePackage> olePackage = shape->get_OleFormat()->get_OlePackage();
olePackage->set_FileName(u"filename.zip");
olePackage->set_DisplayName(u"displayname.zip");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertElements.InsertOleObjectwithOlePackage.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertImage(dataDir + u"Watermark.png", RelativeHorizontalPosition::Margin, 100, RelativeVerticalPosition::Margin, 100, 200, 100, WrapType::Square);
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertImage.InsertFloatingImage.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertImage(dataDir + u"Watermark.png");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertImage.InsertInlineImage.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Specify font formatting
System::SharedPtr<Font> font = builder->get_Font();
font->set_Size(16);
font->set_Bold(true);
font->set_Color(System::Drawing::Color::get_Blue());
font->set_Name(u"Arial");
font->set_Underline(Underline::Dash);
// Specify paragraph formatting
System::SharedPtr<ParagraphFormat> paragraphFormat = builder->get_ParagraphFormat();
paragraphFormat->set_FirstLineIndent(8);
paragraphFormat->set_Alignment(ParagraphAlignment::Justify);
paragraphFormat->set_KeepTogether(true);
builder->Writeln(u"A whole paragraph.");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertParagraph.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Create a document builder to insert content with.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a TC field at the current document builder position.
builder->InsertField(u"TC \"Entry Text\" \\f t");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertTCField.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
// Highlight newly inserted content.
options->get_ApplyFont()->set_HighlightColor(System::Drawing::Color::get_DarkOrange());
options->set_ReplacingCallback(System::MakeObject<InsertTCFieldHandler>(u"Chapter 1", u"\\l 1"));
// Insert a TC field which displays "Chapter 1" just before the text "The Beginning" in the document.
doc->get_Range()->Replace(System::MakeObject<System::Text::RegularExpressions::Regex>(u"The Beginning"), u"", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
class InsertTCFieldHandler : public IReplacingCallback
{
typedef InsertTCFieldHandler ThisType;
typedef IReplacingCallback BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
public:
InsertTCFieldHandler(const System::String& text, const System::String& switches)
: mFieldText(text), mFieldSwitches(switches) {}
InsertTCFieldHandler(const System::String& switches)
: mFieldText(System::String::Empty), mFieldSwitches(switches) {}
ReplaceAction Replacing(System::SharedPtr<ReplacingArgs> args) override;
private:
System::String mFieldText;
System::String mFieldSwitches;
};
ReplaceAction InsertTCFieldHandler::Replacing(System::SharedPtr<ReplacingArgs> args)
{
// Create a builder to insert the field.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(System::DynamicCast<Document>(args->get_MatchNode()->get_Document()));
// Move to the first node of the match.
builder->MoveTo(args->get_MatchNode());
// If the user specified text to be used in the field as display text then use that, otherwise use the
// Match string as the display text.
System::String insertText;
if (!System::String::IsNullOrEmpty(mFieldText))
{
insertText = mFieldText;
}
else
{
insertText = args->get_Match()->get_Value();
}
// Insert the TC field before this node using the specified string as the display text and user defined switches.
builder->InsertField(System::String::Format(u"TC \"{0}\" {1}", insertText, mFieldSwitches));
// We have done what we want so skip replacement.
return ReplaceAction::Skip;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a table of contents at the beginning of the document.
builder->InsertTableOfContents(u"\\o \"1-3\" \\h \\z \\u");
// The newly inserted table of contents will be initially empty.
// It needs to be populated by updating the fields in the document.
doc->UpdateFields();
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderInsertTOC.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
doc->UpdateFields();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Shows how to access the current node in a document builder.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Node> curNode = builder->get_CurrentNode();
System::SharedPtr<Paragraph> curParagraph = builder->get_CurrentParagraph();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Create a blank document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Specify that we want headers and footers different for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header First");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header Even");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header Odd");
// Create three pages in the document.
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page3");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderMovingCursor.HeadersAndFooters.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToBookmark(u"CoolBookmark");
builder->Writeln(u"This is a very cool bookmark.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToBookmark(u"CoolBookmark", false, true);
builder->Writeln(u"This is a very cool bookmark.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToDocumentEnd();
std::cout << "This is the end of the document." << std::endl;
builder->MoveToDocumentStart();
std::cout << "This is the beginning of the document." << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToMergeField(u"NiceMergeField");
builder->Writeln(u"This is a very nice merge field.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_LastParagraph());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Parameters are 0-index. Moves to third paragraph.
builder->MoveToParagraph(2, 0);
builder->Writeln(u"This is the 3rd paragraph.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Parameters are 0-index. Moves to third section.
builder->MoveToSection(2);
builder->Writeln(u"This is the 3rd section.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// All parameters are 0-index. Moves to the 2nd table, 3rd row, 5th cell.
builder->MoveToCell(1, 2, 4, 0);
builder->Writeln(u"Hello World!");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set paragraph borders
System::SharedPtr<BorderCollection> borders = builder->get_ParagraphFormat()->get_Borders();
borders->set_DistanceFromText(20);
borders->idx_get(BorderType::Left)->set_LineStyle(LineStyle::Double);
borders->idx_get(BorderType::Right)->set_LineStyle(LineStyle::Double);
borders->idx_get(BorderType::Top)->set_LineStyle(LineStyle::Double);
borders->idx_get(BorderType::Bottom)->set_LineStyle(LineStyle::Double);
// Set paragraph shading
System::SharedPtr<Shading> shading = builder->get_ParagraphFormat()->get_Shading();
shading->set_Texture(TextureIndex::TextureDiagonalCross);
shading->set_BackgroundPatternColor(System::Drawing::Color::get_LightCoral());
shading->set_ForegroundPatternColor(System::Drawing::Color::get_LightSalmon());
builder->Write(u"I'm a formatted paragraph with double border and nice shading.");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.ApplyBordersAndShadingToParagraph.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set paragraph style
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Title);
builder->Write(u"Hello");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.ApplyParagraphStyle.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set font formatting properties
System::SharedPtr<Font> font = builder->get_Font();
font->set_Bold(true);
font->set_Color(System::Drawing::Color::get_DarkBlue());
font->set_Italic(true);
font->set_Name(u"Arial");
font->set_Size(24);
font->set_Spacing(5);
font->set_Underline(Underline::Double);
// Output formatted text
builder->Writeln(u"I'm a very nice formatted string.");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.SetFontFormatting.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->get_ListFormat()->ApplyNumberDefault();
builder->Writeln(u"Item 1");
builder->Writeln(u"Item 2");
builder->get_ListFormat()->ListIndent();
builder->Writeln(u"Item 2.1");
builder->Writeln(u"Item 2.2");
builder->get_ListFormat()->ListIndent();
builder->Writeln(u"Item 2.2.1");
builder->Writeln(u"Item 2.2.2");
builder->get_ListFormat()->ListOutdent();
builder->Writeln(u"Item 2.3");
builder->get_ListFormat()->ListOutdent();
builder->Writeln(u"Item 3");
builder->get_ListFormat()->RemoveNumbers();
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.SetMultilevelListFormatting.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set page properties
builder->get_PageSetup()->set_Orientation(Orientation::Landscape);
builder->get_PageSetup()->set_LeftMargin(50);
builder->get_PageSetup()->set_PaperSize(PaperSize::Paper10x14);
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.SetPageSetupAndSectionFormatting.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set paragraph formatting properties
System::SharedPtr<ParagraphFormat> paragraphFormat = builder->get_ParagraphFormat();
paragraphFormat->set_Alignment(ParagraphAlignment::Center);
paragraphFormat->set_LeftIndent(50);
paragraphFormat->set_RightIndent(50);
paragraphFormat->set_SpaceAfter(25);
// Output text
builder->Writeln(u"I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
builder->Writeln(u"I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.SetParagraphFormatting.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set paragraph formatting properties
System::SharedPtr<ParagraphFormat> paragraphFormat = builder->get_ParagraphFormat();
paragraphFormat->set_AddSpaceBetweenFarEastAndAlpha(true);
paragraphFormat->set_AddSpaceBetweenFarEastAndDigit(true);
builder->Writeln(u"Automatically adjust space between Asian and Latin text");
builder->Writeln(u"Automatically adjust space between Asian text and numbers");
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.SetSpacebetweenAsianandLatintext.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->StartTable();
builder->InsertCell();
// Set the cell formatting
System::SharedPtr<CellFormat> cellFormat = builder->get_CellFormat();
cellFormat->set_Width(250);
cellFormat->set_LeftPadding(30);
cellFormat->set_RightPadding(30);
cellFormat->set_TopPadding(30);
cellFormat->set_BottomPadding(30);
builder->Writeln(u"I'm a wonderful formatted cell.");
builder->EndRow();
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.SetTableCellFormatting.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
// Set the row formatting
System::SharedPtr<RowFormat> rowFormat = builder->get_RowFormat();
rowFormat->set_Height(100);
rowFormat->set_HeightRule(HeightRule::Exactly);
// These formatting properties are set on the table and are applied to all rows in the table.
table->set_LeftPadding(30);
table->set_RightPadding(30);
table->set_TopPadding(30);
table->set_BottomPadding(30);
builder->Writeln(u"I'm a wonderful formatted row.");
builder->EndRow();
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.SetTableRowFormatting.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Input.docx");
System::SharedPtr<ParagraphFormat> format = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_ParagraphFormat();
format->set_FarEastLineBreakControl(false);
format->set_WordWrap(true);
format->set_HangingPunctuation(false);
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentBuilderSetFormatting.SetAsianTypographyLinebreakGroupProp.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
//Set the layout mode for a section allowing to define the document grid behavior
//Note that the Document Grid tab becomes visible in the Page Setup dialog of MS Word if any Asian language is defined as editing language.
doc->get_FirstSection()->get_PageSetup()->set_LayoutMode(SectionLayoutMode::Grid);
//Set the number of characters per line in the document grid.
doc->get_FirstSection()->get_PageSetup()->set_CharactersPerLine(30);
//Set the number of lines per page in the document grid.
doc->get_FirstSection()->get_PageSetup()->set_LinesPerPage(10);
System::String outputPath = dataDir + GetOutputFilePath(u"DocumentPageSetup.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
System::SharedPtr<Paragraph> startPara = System::DynamicCast<Paragraph>(doc->get_LastSection()->GetChild(NodeType::Paragraph, 2, true));
System::SharedPtr<Table> endTable = System::DynamicCast<Table>(doc->get_LastSection()->GetChild(NodeType::Table, 0, true));
// Extract the content between these nodes in the document. Include these markers in the extraction.
auto extractedNodes = ExtractContent(startPara, endTable, true);
// Lets reverse the array to make inserting the content back into the document easier.
for (auto it = extractedNodes.rbegin(); it != extractedNodes.rend(); ++it)
{
endTable->get_ParentNode()->InsertAfter(*it, endTable);
}
System::String outputPath = dataDir + GetOutputFilePath(u"ExtractContentBetweenBlockLevelNodes.doc");
// Save the generated document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
System::SharedPtr<Section> section = doc->get_Sections()->idx_get(0);
section->get_PageSetup()->set_LeftMargin(70.85);
// Retrieve the bookmark from the document.
System::SharedPtr<Bookmark> bookmark = doc->get_Range()->get_Bookmarks()->idx_get(u"Bookmark1");
// We use the BookmarkStart and BookmarkEnd nodes as markers.
System::SharedPtr<BookmarkStart> bookmarkStart = bookmark->get_BookmarkStart();
System::SharedPtr<BookmarkEnd> bookmarkEnd = bookmark->get_BookmarkEnd();
// Firstly extract the content between these nodes including the bookmark.
auto extractedNodesInclusive = ExtractContent(bookmarkStart, bookmarkEnd, true);
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodesInclusive);
System::String inclusiveOutputPath = dataDir + GetOutputFilePath(u"ExtractContentBetweenBookmark.Inclusive.doc");
dstDoc->Save(inclusiveOutputPath);
std::cout << "File saved at " << inclusiveOutputPath.ToUtf8String() << std::endl;
// Secondly extract the content between these nodes this time without including the bookmark.
auto extractedNodesExclusive = ExtractContent(bookmarkStart, bookmarkEnd, false);
dstDoc = GenerateDocument(doc, extractedNodesExclusive);
System::String exclusiveOutputPath = dataDir + GetOutputFilePath(u"ExtractContentBetweenBookmark.Exclusive.doc");
dstDoc->Save(exclusiveOutputPath);
std::cout << "File saved at " << exclusiveOutputPath.ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// This is a quick way of getting both comment nodes.
// Your code should have a proper method of retrieving each corresponding start and end node.
System::SharedPtr<CommentRangeStart> commentStart = System::DynamicCast<CommentRangeStart>(doc->GetChild(NodeType::CommentRangeStart, 0, true));
System::SharedPtr<CommentRangeEnd> commentEnd = System::DynamicCast<CommentRangeEnd>(doc->GetChild(NodeType::CommentRangeEnd, 0, true));
// Firstly extract the content between these nodes including the comment as well.
auto extractedNodesInclusive = ExtractContent(commentStart, commentEnd, true);
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodesInclusive);
System::String inclusiveOutputPath = dataDir + GetOutputFilePath(u"ExtractContentBetweenCommentRange.Inclusive.doc");
dstDoc->Save(inclusiveOutputPath);
std::cout << "File saved at " << inclusiveOutputPath.ToUtf8String() << std::endl;
// Secondly extract the content between these nodes without the comment.
auto extractedNodesExclusive = ExtractContent(commentStart, commentEnd, false);
dstDoc = GenerateDocument(doc, extractedNodesExclusive);
System::String exclusiveOutputPath = dataDir + GetOutputFilePath(u"ExtractContentBetweenCommentRange.Exclusive.doc");
dstDoc->Save(exclusiveOutputPath);
std::cout << "File saved at " << exclusiveOutputPath.ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Gather the nodes. The GetChild method uses 0-based index
System::SharedPtr<Paragraph> startPara = System::DynamicCast<Paragraph>(doc->get_FirstSection()->get_Body()->GetChild(NodeType::Paragraph, 6, true));
System::SharedPtr<Paragraph> endPara = System::DynamicCast<Paragraph>(doc->get_FirstSection()->get_Body()->GetChild(NodeType::Paragraph, 10, true));
// Extract the content between these nodes in the document. Include these markers in the extraction.
auto extractedNodes = ExtractContent(startPara, endPara, true);
// Insert the content into a new separate document and save it to disk.
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodes);
System::String outputPath = dataDir + GetOutputFilePath(u"ExtractContentBetweenParagraphs.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Gather a list of the paragraphs using the respective heading styles.
auto parasStyleHeading1 = ParagraphsByStyleName(doc, u"Heading 1");
auto parasStyleHeading3 = ParagraphsByStyleName(doc, u"Heading 3");
// Use the first instance of the paragraphs with those styles.
System::SharedPtr<Node> startPara1 = parasStyleHeading1[0];
System::SharedPtr<Node> endPara1 = parasStyleHeading3[0];
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
auto extractedNodes = ExtractContent(startPara1, endPara1, false);
// Insert the content into a new separate document and save it to disk.
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodes);
System::String outputPath = dataDir + GetOutputFilePath(u"ExtractContentBetweenParagraphStyles.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Retrieve a paragraph from the first section.
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 7, true));
// Use some runs for extraction.
System::SharedPtr<Run> startRun = para->get_Runs()->idx_get(1);
System::SharedPtr<Run> endRun = para->get_Runs()->idx_get(4);
// Extract the content between these nodes in the document. Include these markers in the extraction.
auto extractedNodes = ExtractContent(startRun, endRun, true);
// Get the node from the list. There should only be one paragraph returned in the list.
System::SharedPtr<Node> node = extractedNodes[0];
// Print the text of this node to the console.
std::cout << node->ToString(SaveFormat::Text).ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Use a document builder to retrieve the field start of a merge field.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field.
// We could also get FieldStarts of a field using GetChildNode method as in the other examples.
builder->MoveToMergeField(u"Fullname", false, false);
// The builder cursor should be positioned at the start of the field.
System::SharedPtr<FieldStart> startField = System::DynamicCast<FieldStart>(builder->get_CurrentNode());
System::SharedPtr<Paragraph> endPara = System::DynamicCast<Paragraph>(doc->get_FirstSection()->GetChild(NodeType::Paragraph, 5, true));
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startField, endPara, false);
// Insert the content into a new separate document and save it to disk.
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodes);
System::String outputPath = dataDir + GetOutputFilePath(u"ExtractContentUsingField.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Enter a dummy field into the document.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD Field");
// GetText will retrieve all field codes and special characters
std::cout << "GetText() Result: " << doc->GetText().ToUtf8String() << std::endl;
// ToString will export the node to the specified format. When converted to text it will not retrieve fields code
// Or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
// This is the same as "viewing" the document as if it was opened in a text editor.
std::cout << "ToString() Result: " << doc->ToString(SaveFormat::Text).ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Load the template document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
System::String variables = u"";
for (System::Collections::Generic::KeyValuePair<System::String, System::String> entry : System::IterateOver(doc->get_Variables()))
{
System::String name = entry.get_Key();
System::String value = entry.get_Value();
if (variables == u"")
{
// Do something useful.
variables = System::String(u"Name: ") + name + u"," + u"Value: " + value;
}
else
{
variables = variables + u"Name: " + name + u"," + u"Value: " + value;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// Should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
void InsertDocument(System::SharedPtr<Node> insertAfterNode, const System::SharedPtr<Document>& srcDoc)
{
// Make sure that the node is either a paragraph or table.
if (insertAfterNode->get_NodeType() != NodeType::Paragraph && insertAfterNode->get_NodeType() != NodeType::Table)
{
throw System::ArgumentException(u"The destination node should be either a paragraph or table.");
}
// We will be inserting into the parent of the destination paragraph.
System::SharedPtr<CompositeNode> dstStory = insertAfterNode->get_ParentNode();
// This object will be translating styles and lists during the import.
System::SharedPtr<NodeImporter> importer = System::MakeObject<NodeImporter>(srcDoc, insertAfterNode->get_Document(), ImportFormatMode::KeepSourceFormatting);
// Loop through all sections in the source document.
for (System::SharedPtr<Section> srcSection : System::IterateOver<System::SharedPtr<Section>>(srcDoc->get_Sections()))
{
// Loop through all block level nodes (paragraphs and tables) in the body of the section.
for (System::SharedPtr<Node> srcNode : System::IterateOver(srcSection->get_Body()))
{
// Let's skip the node if it is a last empty paragraph in a section.
if (srcNode->get_NodeType() == NodeType::Paragraph)
{
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(srcNode);
if (para->get_IsEndOfSection() && !para->get_HasChildNodes())
{
continue;
}
}
// This creates a clone of the node, suitable for insertion into the destination document.
System::SharedPtr<Node> newNode = importer->ImportNode(srcNode, true);
// Insert new node after the reference node.
dstStory->InsertAfter(newNode, insertAfterNode);
insertAfterNode = newNode;
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> mainDoc = System::MakeObject<Document>(dataDir + u"InsertDocument1.doc");
System::SharedPtr<Document> subDoc = System::MakeObject<Document>(dataDir + u"InsertDocument2.doc");
System::SharedPtr<Bookmark> bookmark = mainDoc->get_Range()->get_Bookmarks()->idx_get(u"insertionPlace");
InsertDocument(bookmark->get_BookmarkStart()->get_ParentNode(), subDoc);
System::String outputPath = dataDir + GetOutputFilePath(u"InsertDoc.InsertDocumentAtBookmark.doc");
mainDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Open the main document.
typedef System::SharedPtr<System::Object> TObjectPtr;
System::SharedPtr<Document> mainDoc = System::MakeObject<Document>(dataDir + u"InsertDocument1.doc");
// Add a handler to MergeField event
mainDoc->get_MailMerge()->set_FieldMergingCallback(System::MakeObject<InsertDocumentAtMailMergeHandler>());
// The main document has a merge field in it called "Document_1".
// The corresponding data for this field contains fully qualified path to the document
// That should be inserted to this field.
mainDoc->get_MailMerge()->Execute(System::MakeArray<System::String>({u"Document_1"}), System::StaticCastArray<TObjectPtr>(System::MakeArray<System::String>({dataDir + u"InsertDocument2.doc"})));
System::String outputPath = dataDir + GetOutputFilePath(u"InsertDoc.InsertDocumentAtMailMerge.doc");
mainDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> mainDoc = System::MakeObject<Document>(dataDir + u"InsertDocument1.doc");
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
options->set_ReplacingCallback(System::MakeObject<InsertDocumentAtReplaceHandler>());
mainDoc->get_Range()->Replace(System::MakeObject<System::Text::RegularExpressions::Regex>(u"\\[MY_DOCUMENT\\]"), u"", options);
System::String outputPath = dataDir + GetOutputFilePath(u"InsertDoc.InsertDocumentAtReplace.doc");
mainDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
class InsertDocumentAtReplaceHandler : public IReplacingCallback
{
typedef InsertDocumentAtReplaceHandler ThisType;
typedef IReplacingCallback BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
public:
ReplaceAction Replacing(System::SharedPtr<ReplacingArgs> e) override;
};
ReplaceAction InsertDocumentAtReplaceHandler::Replacing(System::SharedPtr<ReplacingArgs> e)
{
System::SharedPtr<Document> subDoc = System::MakeObject<Document>(GetDataDir_WorkingWithDocument() + u"InsertDocument2.doc");
// Insert a document after the paragraph, containing the match text.
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(e->get_MatchNode()->get_ParentNode());
InsertDocument(para, subDoc);
// Remove the paragraph with the match text.
para->Remove();
return ReplaceAction::Skip;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputFileName);
ProtectionType protectionType = doc->get_ProtectionType();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputFileName);
doc->Protect(ProtectionType::AllowOnlyFormFields, u"password");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputFileName);
doc->Unprotect();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void RemovePageBreaks(const System::SharedPtr<Document>& doc)
{
// Retrieve all paragraphs in the document.
System::SharedPtr<NodeCollection> paragraphs = doc->GetChildNodes(NodeType::Paragraph, true);
// Iterate through all paragraphs
for (System::SharedPtr<Paragraph> para : System::IterateOver<System::SharedPtr<Paragraph>>(paragraphs))
{
// If the paragraph has a page break before set then clear it.
if (para->get_ParagraphFormat()->get_PageBreakBefore())
{
para->get_ParagraphFormat()->set_PageBreakBefore(false);
}
// Check all runs in the paragraph for page breaks and remove them.
for (System::SharedPtr<Run> run : System::IterateOver<System::SharedPtr<Run>>(para->get_Runs()))
{
if (run->get_Text().Contains(ControlChar::PageBreak()))
{
run->set_Text(run->get_Text().Replace(ControlChar::PageBreak(), System::String::Empty));
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void RemoveSectionBreaks(const System::SharedPtr<Document>& doc)
{
// Loop through all sections starting from the section that precedes the last one
// And moving to the first section.
for (int32_t i = doc->get_Sections()->get_Count() - 2; i >= 0; i--)
{
// Copy the content of the current section to the beginning of the last section.
doc->get_LastSection()->PrependContent(doc->get_Sections()->idx_get(i));
// Remove the copied section.
doc->get_Sections()->idx_get(i)->Remove();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"HeaderFooter.RemoveFooters.doc");
for (System::SharedPtr<Section> section : System::IterateOver<System::SharedPtr<Section>>(doc))
{
// Up to three different footers are possible in a section (for first, even and odd pages).
// We check and delete all of them.
System::SharedPtr<HeaderFooter> footer;
footer = section->get_HeadersFooters()->idx_get(HeaderFooterType::FooterFirst);
if (footer != nullptr)
{
footer->Remove();
}
// Primary footer is the footer used for odd pages.
footer = section->get_HeadersFooters()->idx_get(HeaderFooterType::FooterPrimary);
if (footer != nullptr)
{
footer->Remove();
}
footer = section->get_HeadersFooters()->idx_get(HeaderFooterType::FooterEven);
if (footer != nullptr)
{
footer->Remove();
}
}
System::String outputPath = dataDir + GetOutputFilePath(u"RemoveFooters.doc");
// Save the document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
/// <summary>
/// Removes the specified table of contents field from the document.
/// </summary>
/// <param name="doc">The document to remove the field from.</param>
/// <param name="index">The zero-based index of the TOC to remove.</param>
void RemoveTableOfContents(const System::SharedPtr<Document>& doc, int32_t index)
{
// Store the FieldStart nodes of TOC fields in the document for quick access.
std::vector<System::SharedPtr<FieldStart>> fieldStarts;
// This is a list to store the nodes found inside the specified TOC. They will be removed
// At the end of this method.
std::vector<System::SharedPtr<Node>> nodeList;
for (System::SharedPtr<FieldStart> start : System::IterateOver<System::SharedPtr<FieldStart>>(doc->GetChildNodes(NodeType::FieldStart, true)))
{
if (start->get_FieldType() == FieldType::FieldTOC)
{
// Add all FieldStarts which are of type FieldTOC.
fieldStarts.push_back(start);
}
}
// Ensure the TOC specified by the passed index exists.
if (index > fieldStarts.size() - 1)
{
throw System::ArgumentOutOfRangeException(u"TOC index is out of range");
}
bool isRemoving = true;
// Get the FieldStart of the specified TOC.
System::SharedPtr<Node> currentNode = fieldStarts[index];
while (isRemoving)
{
// It is safer to store these nodes and delete them all at once later.
nodeList.push_back(currentNode);
currentNode = currentNode->NextPreOrder(doc);
// Once we encounter a FieldEnd node of type FieldTOC then we know we are at the end
// Of the current TOC and we can stop here.
if (currentNode->get_NodeType() == NodeType::FieldEnd)
{
System::SharedPtr<FieldEnd> fieldEnd = System::DynamicCast<FieldEnd>(currentNode);
if (fieldEnd->get_FieldType() == FieldType::FieldTOC)
{
isRemoving = false;
}
}
}
// Remove all nodes found in the specified TOC.
for (auto& node : nodeList)
{
node->Remove();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithStyles();
// Open a document which contains a TOC.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.TableOfContents.doc");
// Remove the first table of contents from the document.
RemoveTableOfContents(doc, 0);
System::String outputPath = dataDir + GetOutputFilePath(u"RemoveTOCFromDocument.doc");
// Save the output.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<StructuredDocumentTag> sdtRichText = System::MakeObject<StructuredDocumentTag>(doc, SdtType::RichText, MarkupLevel::Block);
System::SharedPtr<Paragraph> para = System::MakeObject<Paragraph>(doc);
System::SharedPtr<Run> run = System::MakeObject<Run>(doc);
run->set_Text(u"Hello World");
run->get_Font()->set_Color(System::Drawing::Color::get_Green());
para->get_Runs()->Add(run);
sdtRichText->get_ChildNodes()->Add(para);
doc->get_FirstSection()->get_Body()->AppendChild(sdtRichText);
System::String outputPath = dataDir + GetOutputFilePath(u"RichTextBoxContentControl.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.docx");
doc->get_CompatibilityOptions()->OptimizeFor(MsWordVersion::Word2016);
System::String outputPath = dataDir + GetOutputFilePath(u"SetCompatibilityOptions.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
loadOptions->get_LanguagePreferences()->AddEditingLanguage(EditingLanguage::Japanese);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"languagepreferences.doc", loadOptions);
int32_t localeIdFarEast = doc->get_Styles()->get_DefaultFont()->get_LocaleIdFarEast();
if (localeIdFarEast == static_cast<int32_t>(EditingLanguage::Japanese))
{
std::cout << "The document either has no any FarEast language set in defaults or it was set to Japanese originally." << std::endl;
}
else
{
std::cout << "The document default FarEast language was set to another than Japanese language originally, so it is not overridden." << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
loadOptions->get_LanguagePreferences()->SetAsDefault(EditingLanguage::Russian);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"languagepreferences.doc", loadOptions);
int32_t localeId = doc->get_Styles()->get_DefaultFont()->get_LocaleId();
if (localeId == static_cast<int32_t>(EditingLanguage::Russian))
{
std::cout << "The document either has no any language set in defaults or it was set to Russian originally." << std::endl;
}
else
{
std::cout << "The document default language was set to another than Russian language originally, so it is not overridden." << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Load the template document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Set view option.
doc->get_ViewOptions()->set_ViewType(ViewType::PageLayout);
doc->get_ViewOptions()->set_ZoomPercent(50);
System::String outputPath = dataDir + GetOutputFilePath(u"SetViewOption.doc");
// Save the finished document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Open an existing document
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"CheckBoxTypeContentControl.docx");
for (System::SharedPtr<StructuredDocumentTag> sdt : System::IterateOver<System::SharedPtr<StructuredDocumentTag>>(doc->GetChildNodes(NodeType::StructuredDocumentTag, true)))
{
if (sdt->get_SdtType() == SdtType::PlainText)
{
sdt->RemoveAllChildren();
System::SharedPtr<Paragraph> para = System::DynamicCast_noexcept<Paragraph>(sdt->AppendChild(System::MakeObject<Paragraph>(doc)));
System::SharedPtr<Run> run = System::MakeObject<Run>(doc, u"new text goes here");
para->AppendChild(run);
}
else if (sdt->get_SdtType() == SdtType::DropDownList)
{
System::SharedPtr<SdtListItem> secondItem = sdt->get_ListItems()->idx_get(2);
sdt->get_ListItems()->set_SelectedValue(secondItem);
}
else if (sdt->get_SdtType() == SdtType::Picture)
{
System::SharedPtr<Shape> shape = System::DynamicCast<Shape>(sdt->GetChild(NodeType::Shape, 0, true));
if (shape->get_HasImage())
{
shape->get_ImageData()->SetImage(dataDir + u"Watermark.png");
}
}
}
System::String outputPath = dataDir + GetOutputFilePath(u"UpdateContentControls.ModifyContentControls.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Open an existing document
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"CheckBoxTypeContentControl.docx");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Get the first content control from the document
System::SharedPtr<StructuredDocumentTag> SdtCheckBox = System::DynamicCast<StructuredDocumentTag>(doc->GetChild(NodeType::StructuredDocumentTag, 0, true));
// StructuredDocumentTag.Checked property gets/sets current state of the Checkbox SDT
if (SdtCheckBox->get_SdtType() == SdtType::Checkbox)
{
SdtCheckBox->set_Checked(true);
}
System::String outputPath = dataDir + GetOutputFilePath(u"UpdateContentControls.SetCurrentStateOfCheckBox.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"TestFile.docx");
auto builder = System::MakeObject<DocumentBuilder>(doc);
builder->Write(u"Some text");
builder->InsertFootnote(FootnoteType::Endnote, u"Eootnote text.");
auto option = doc->get_EndnoteOptions();
option->set_RestartRule(FootnoteNumberingRule::RestartPage);
option->set_Position(EndnotePosition::EndOfSection);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithFootnote.SetEndnoteOptions.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"TestFile.docx");
//Set footnote and endnode position.
doc->get_FootnoteOptions()->set_Position(FootnotePosition::BeneathText);
doc->get_EndnoteOptions()->set_Position(EndnotePosition::EndOfSection);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithFootnote.SetFootnoteAndEndNotePosition.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"TestFile.docx");
//Specify the number of columns with which the footnotes area is formatted.
doc->get_FootnoteOptions()->set_Columns(3);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithFootnote.SetFootNoteColumns.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
// Start tracking and make some revisions.
doc->StartTrackRevisions(u"Author");
doc->get_FirstSection()->get_Body()->AppendParagraph(u"Hello world!");
// Revisions will now show up as normal text in the output document.
doc->AcceptAllRevisions();
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithRevisions.AcceptRevisions.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Revisions.docx");
for (System::SharedPtr<RevisionGroup> group : System::IterateOver(doc->get_Revisions()->get_Groups()))
{
std::cout << group->get_Author().ToUtf8String() << ", :" << System::ObjectExt::Box<RevisionType>(group->get_RevisionType())->ToString().ToUtf8String() << std::endl;
std::cout << group->get_Text().ToUtf8String() << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Revisions.docx");
System::SharedPtr<ParagraphCollection> paragraphs = doc->get_FirstSection()->get_Body()->get_Paragraphs();
for (int32_t i = 0; i < paragraphs->get_Count(); i++)
{
if (paragraphs->idx_get(i)->get_IsMoveFromRevision())
{
std::cout << "The paragraph " << i << " has been moved (deleted)." << std::endl;
}
if (paragraphs->idx_get(i)->get_IsMoveToRevision())
{
std::cout << "The paragraph " << i << " has been moved (inserted)." << std::endl;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Specify font formatting before adding text.
System::SharedPtr<Font> font = builder->get_Font();
font->set_Size(16);
font->set_Bold(true);
font->set_Color(System::Drawing::Color::get_Blue());
font->set_Name(u"Arial");
font->set_Underline(Underline::Dash);
builder->Write(u"Sample text.");
System::String outputPath = dataDir + GetOutputFilePath(u"WriteAndFont.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
// We will test this functionality creating a document with two fields with date formatting
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert content with German locale.
builder->get_Font()->set_LocaleId(1031);
builder->InsertField(u"MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
builder->Write(u" - ");
builder->InsertField(u"MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");
// Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from.
// Set the culture used during field update to the culture used by the field.
doc->get_FieldOptions()->set_FieldUpdateCultureSource(FieldUpdateCultureSource::FieldCode);
doc->get_MailMerge()->Execute(System::MakeArray<System::String>({u"Date2"}), System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::DateTime>(System::DateTime(2011, 1, 1))}));
System::String outputPath = dataDir + GetOutputFilePath(u"ChangeFieldUpdateCultureSource.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert content with German locale.
builder->get_Font()->set_LocaleId(1031);
builder->InsertField(u"MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
builder->Write(u" - ");
builder->InsertField(u"MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
// Create a blank document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> b = System::MakeObject<DocumentBuilder>(doc);
b->InsertField(u"MERGEFIELD Date");
// Store the current culture so it can be set back once mail merge is complete.
System::SharedPtr<System::Globalization::CultureInfo> currentCulture = System::Threading::Thread::get_CurrentThread()->get_CurrentCulture();
// Set to German language so dates and numbers are formatted using this culture during mail merge.
System::Threading::Thread::get_CurrentThread()->set_CurrentCulture(System::MakeObject<System::Globalization::CultureInfo>(u"de-DE"));
// Execute mail merge.
doc->get_MailMerge()->Execute(System::MakeArray<System::String>({u"Date"}), System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::DateTime>(System::DateTime::get_Now())}));
// Restore the original culture.
System::Threading::Thread::get_CurrentThread()->set_CurrentCulture(currentCulture);
System::String outputPath = dataDir + GetOutputFilePath(u"ChangeLocale.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Pass the appropriate parameters to convert PAGE fields encountered to static text only in the body of the first section.
ConvertFieldsToStaticText(doc->get_FirstSection()->get_Body(), FieldType::FieldPage);
System::String outputPath = dataDir + GetOutputFilePath(u"ConvertFieldsInBody.doc");
// Save the document with fields transformed to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Pass the appropriate parameters to convert all IF fields encountered in the document (including headers and footers) to static text.
ConvertFieldsToStaticText(doc, FieldType::FieldIf);
System::String outputPath = dataDir + GetOutputFilePath(u"ConvertFieldsInDocument.doc");
// Save the document with fields transformed to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Pass the appropriate parameters to convert all IF fields to static text that are encountered only in the last
// Paragraph of the document.
ConvertFieldsToStaticText(doc->get_FirstSection()->get_Body()->get_LastParagraph(), FieldType::FieldIf);
System::String outputPath = dataDir + GetOutputFilePath(u"ConvertFieldsInParagraph.doc");
// Save the document with fields transformed to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>();
System::SharedPtr<FieldIf> field = System::DynamicCast<FieldIf>(builder->InsertField(u"IF 1 = 1", nullptr));
FieldIfComparisonResult actualResult = field->EvaluateCondition();
std::cout << System::ObjectExt::Box<FieldIfComparisonResult>(actualResult)->ToString().ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void ConvertFieldsToStaticText(System::SharedPtr<CompositeNode> compositeNode, FieldType targetFieldType)
{
for (System::SharedPtr<Field> field : System::IterateOver(compositeNode->get_Range()->get_Fields()))
{
if (field->get_Type() == targetFieldType)
{
field->Unlink();
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"FormFields.doc");
System::SharedPtr<FormFieldCollection> documentFormFields = doc->get_Range()->get_FormFields();
System::SharedPtr<FormField> formField1 = documentFormFields->idx_get(3);
System::SharedPtr<FormField> formField2 = documentFormFields->idx_get(u"Text2");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"FormFields.doc");
System::SharedPtr<FormFieldCollection> formFields = doc->get_Range()->get_FormFields();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"FormFields.doc");
System::SharedPtr<FormField> formField = doc->get_Range()->get_FormFields()->idx_get(3);
if (formField->get_Type() == FieldType::FieldFormTextInput)
{
formField->set_Result(System::String(u"My name is ") + formField->get_Name());
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Shows how to get names of all merge fields in a document.
System::ArrayPtr<System::String> fieldNames = doc->get_MailMerge()->GetFieldNames();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"in.doc");
// Get paragraph you want to append this Advance field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an Advance field like this:
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
// Create instance of FieldAdvance class and lets build the above field code
System::SharedPtr<FieldAdvance> field = System::DynamicCast<FieldAdvance>(para->AppendField(FieldType::FieldAdvance, false));
// { ADVANCE \\d 10 " }
field->set_DownOffset(u"10");
// { ADVANCE \\d 10 \\l 10 }
field->set_LeftOffset(u"10");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 }
field->set_RightOffset(u"-3.3");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 }
field->set_UpOffset(u"0");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 }
field->set_HorizontalPosition(u"100");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
field->set_VerticalPosition(u"100");
// Finally update this Advance field
field->Update();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertAdvanceFieldWithoutDocumentBuilder.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"in.doc");
// Get paragraph you want to append this Ask field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an Ask field like this:
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
// Create instance of FieldAsk class and lets build the above field code
System::SharedPtr<FieldAsk> field = System::DynamicCast<FieldAsk>(para->AppendField(FieldType::FieldAsk, false));
// { ASK \"Test 1\" " }
field->set_BookmarkName(u"Test 1");
// { ASK \"Test 1\" Test2 }
field->set_PromptText(u"Test2");
// { ASK \"Test 1\" Test2 \\d Test3 }
field->set_DefaultResponse(u"Test3");
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
field->set_PromptOnceOnMailMerge(true);
// Finally update this Ask field
field->Update();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertASKFieldWithoutDocumentBuilder.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"in.doc");
// Get paragraph you want to append this AUTHOR field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an AUTHOR field like this:
// { AUTHOR Test1 }
// Create instance of FieldAuthor class and lets build the above field code
System::SharedPtr<FieldAuthor> field = System::DynamicCast<FieldAuthor>(para->AppendField(FieldType::FieldAuthor, false));
// { AUTHOR Test1 }
field->set_AuthorName(u"Test1");
// Finally update this AUTHOR field
field->Update();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertAuthorField.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD MyFieldName \\* MERGEFORMAT");
System::String outputPath = dataDir + GetOutputFilePath(u"InsertField.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::ArrayPtr<System::String> items = System::MakeArray<System::String>({u"One", u"Two", u"Three"});
builder->InsertComboBox(u"DropDown", items, 0);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"in.doc");
// Get paragraph you want to append this INCLUDETEXT field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
// Create instance of FieldAsk class and lets build the above field code
System::SharedPtr<FieldIncludeText> fieldIncludeText = System::DynamicCast<FieldIncludeText>(para->AppendField(FieldType::FieldIncludeText, false));
fieldIncludeText->set_BookmarkName(u"bookmark");
fieldIncludeText->set_SourceFullName(dataDir + u"IncludeText.docx");
doc->get_FirstSection()->get_Body()->AppendChild(para);
// Finally update this IncludeText field
fieldIncludeText->Update();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertIncludeTextFieldWithoutDocumentBuilder.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"in.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Get paragraph you want to append this merge field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// Move cursor to this paragraph
builder->MoveTo(para);
// We want to insert a mail merge address block like this:
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
// Create instance of FieldAddressBlock class and lets build the above field code
System::SharedPtr<FieldAddressBlock> field = System::DynamicCast<FieldAddressBlock>(builder->InsertField(FieldType::FieldAddressBlock, false));
// { ADDRESSBLOCK \\c 1" }
field->set_IncludeCountryOrRegionName(u"1");
// { ADDRESSBLOCK \\c 1 \\d" }
field->set_FormatAddressOnCountryOrRegion(true);
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 }
field->set_ExcludedCountryOrRegionName(u"Test2");
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 }
field->set_NameAndAddressFormat(u"Test3");
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
field->set_LanguageId(u"Test 4");
// Finally update this merge field
field->Update();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertMailMergeAddressBlockFieldUsingDOM.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"in.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Get paragraph you want to append this merge field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// Move cursor to this paragraph
builder->MoveTo(para);
// We want to insert a merge field like this:
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
// Create instance of FieldMergeField class and lets build the above field code
System::SharedPtr<FieldMergeField> field = System::DynamicCast<FieldMergeField>(builder->InsertField(FieldType::FieldMergeField, false));
// { " MERGEFIELD Test1" }
field->set_FieldName(u"Test1");
// { " MERGEFIELD Test1 \\b Test2" }
field->set_TextBefore(u"Test2");
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 }
field->set_TextAfter(u"Test3");
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m" }
field->set_IsMapped(true);
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
field->set_IsVerticalFormatting(true);
// Finally update this merge field
field->Update();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertMergeFieldUsingDOM.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a few page breaks (just for testing)
for (int32_t i = 0; i < 5; i++)
{
builder->InsertBreak(BreakType::PageBreak);
}
// Move the DocumentBuilder cursor into the primary footer.
builder->MoveToHeaderFooter(HeaderFooterType::FooterPrimary);
// We want to insert a field like this:
// { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" }
System::SharedPtr<Field> field = builder->InsertField(u"IF ");
builder->MoveTo(field->get_Separator());
builder->InsertField(u"PAGE");
builder->Write(u" <> ");
builder->InsertField(u"NUMPAGES");
builder->Write(u" \"See Next Page\" \"Last Page\" ");
// Finally update the outer field to recalculate the final value. Doing this will automatically update
// The inner fields at the same time.
field->Update();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertNestedFields.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"in.doc");
// Get paragraph you want to append this TOA field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert TA and TOA fields like this:
// { TA \c 1 \l "Value 0" }
// { TOA \c 1 }
// Create instance of FieldAsk class and lets build the above field code
System::SharedPtr<FieldTA> fieldTA = System::DynamicCast<FieldTA>(para->AppendField(FieldType::FieldTOAEntry, false));
fieldTA->set_EntryCategory(u"1");
fieldTA->set_LongCitation(u"Value 0");
doc->get_FirstSection()->get_Body()->AppendChild(para);
para = System::MakeObject<Paragraph>(doc);
// Create instance of FieldToa class
System::SharedPtr<FieldToa> fieldToa = System::DynamicCast<FieldToa>(para->AppendField(FieldType::FieldTOA, false));
fieldToa->set_EntryCategory(u"1");
doc->get_FirstSection()->get_Body()->AppendChild(para);
// Finally update this TOA field
fieldToa->Update();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertTOAFieldWithoutDocumentBuilder.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Field.RemoveField.doc");
System::SharedPtr<Field> field = doc->get_Range()->get_Fields()->idx_get(0);
// Calling this method completely removes the field from the document.
field->Remove();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
/// <summary>
/// Represents a facade object for a merge field in a Microsoft Word document.
/// </summary>
class MergeField
{
public:
MergeField(const System::SharedPtr<FieldStart>& fieldStart);
/// <summary>
/// Gets the name of the merge field.
/// </summary>
System::String GetName() { return (System::DynamicCast<FieldStart>(mFieldStart))->GetField()->get_Result().Replace(u"«", u"").Replace(u"»", u""); }
/// <summary>
/// Sets the name of the merge field.
/// </summary>
void SetName(const System::String &value);
private:
void UpdateFieldCode(const System::String &fieldName);
/// <summary>
/// Removes nodes from start up to but not including the end node.
/// Start and end are assumed to have the same parent.
/// </summary>
static void RemoveSameParent(const System::SharedPtr<Node>& startNode, const System::SharedPtr<Node>& endNode);
static System::Text::RegularExpressions::Regex& gRegex();
System::SharedPtr<Node> mFieldStart;
System::SharedPtr<Node> mFieldSeparator;
System::SharedPtr<Node> mFieldEnd;
};
MergeField::MergeField(const System::SharedPtr<FieldStart>& fieldStart) : mFieldStart(fieldStart)
{
if (!fieldStart)
{
throw System::ArgumentNullException(u"fieldStart");
}
if (fieldStart->get_FieldType() != FieldType::FieldMergeField)
{
throw System::ArgumentException(u"Field start type must be FieldMergeField.");
}
mFieldSeparator = fieldStart->GetField()->get_Separator();
if (mFieldSeparator == nullptr)
{
throw System::InvalidOperationException(u"Cannot find field separator.");
}
mFieldEnd = fieldStart->GetField()->get_FieldEnd();
}
void MergeField::SetName(const System::String &value)
{
// Merge field name is stored in the field result which is a Run
// Node between field separator and field end.
auto fieldResult = System::DynamicCast<Run>(mFieldSeparator->get_NextSibling());
fieldResult->set_Text(System::String::Format(u"«{0}»", value));
// But sometimes the field result can consist of more than one run, delete these runs.
RemoveSameParent(fieldResult->get_NextSibling(), mFieldEnd);
UpdateFieldCode(value);
}
void MergeField::UpdateFieldCode(const System::String &fieldName)
{
// Field code is stored in a Run node between field start and field separator.
System::SharedPtr<Run> fieldCode = System::DynamicCast<Run>(mFieldStart->get_NextSibling());
System::SharedPtr<System::Text::RegularExpressions::Match> match = gRegex().Match((System::DynamicCast<FieldStart>(mFieldStart))->GetField()->GetFieldCode());
System::String newFieldCode = System::String::Format(u" {0}{1} ", match->get_Groups()->idx_get(u"start")->get_Value(), fieldName);
fieldCode->set_Text(newFieldCode);
// But sometimes the field code can consist of more than one run, delete these runs.
RemoveSameParent(fieldCode->get_NextSibling(), mFieldSeparator);
}
void MergeField::RemoveSameParent(const System::SharedPtr<Node>& startNode, const System::SharedPtr<Node>& endNode)
{
if ((endNode != nullptr) && startNode->get_ParentNode() != endNode->get_ParentNode())
{
throw System::ArgumentException(u"Start and end nodes are expected to have the same parent.");
}
System::SharedPtr<Node> curChild = startNode;
while ((curChild != nullptr) && (curChild != endNode))
{
System::SharedPtr<Node> nextChild = curChild->get_NextSibling();
curChild->Remove();
curChild = nextChild;
}
}
System::Text::RegularExpressions::Regex& MergeField::gRegex()
{
static System::SharedPtr<System::Text::RegularExpressions::Regex> gRegex = System::MakeObject<System::Text::RegularExpressions::Regex>(u"\\s*(?<start>MERGEFIELD\\s|)(\\s|)(?<name>\\S+)\\s+");
return *gRegex;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
// Specify your document name here.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"RenameMergeFields.doc");
// Select all field start nodes so we can find the merge fields.
System::SharedPtr<NodeCollection> fieldStarts = doc->GetChildNodes(NodeType::FieldStart, true);
for (System::SharedPtr<FieldStart> fieldStart : System::IterateOver<System::SharedPtr<FieldStart>>(fieldStarts))
{
if (fieldStart->get_FieldType() == FieldType::FieldMergeField)
{
MergeField mergeField{fieldStart};
mergeField.SetName(mergeField.GetName() + u"_Renamed");
}
}
System::String outputPath = dataDir + GetOutputFilePath(u"RenameMergeFields.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>();
System::SharedPtr<Field> field = builder->InsertField(FieldType::FieldDate, true);
field->set_LocaleId(1049);
builder->get_Document()->Save(dataDir + GetOutputFilePath(u"SpecifylocaleAtFieldlevel.docx"));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Rendering.doc");
// This updates all fields in the document.
doc->UpdateFields();
System::String outputPath = dataDir + GetOutputFilePath(u"UpdateDocFields.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"MathEquations.docx");
System::SharedPtr<OfficeMath> officeMath = System::DynamicCast<OfficeMath>(doc->GetChild(NodeType::OfficeMath, 0, true));
// Gets/sets Office Math display format type which represents whether an equation is displayed inline with the text or displayed on its own line.
officeMath->set_DisplayType(OfficeMathDisplayType::Display);
// or OfficeMathDisplayType.Inline
// Gets/sets Office Math justification.
officeMath->set_Justification(OfficeMathJustification::Left);
// Left justification of Math Paragraph.
System::String outputPath = dataDir + GetOutputFilePath(u"UseOfficeMathProperties.docx");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_FindAndReplace();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
options->set_ReplacingCallback(System::MakeObject<ReplaceEvaluatorFindAndHighlight>());
options->set_Direction(FindReplaceDirection::Backward);
// We want the "your document" phrase to be highlighted.
auto regex = System::MakeObject<Regex>(u"your document", RegexOptions::IgnoreCase);
doc->get_Range()->Replace(regex, u"", options);
System::String outputPath = dataDir + GetOutputFilePath(u"FindAndHighlight.doc");
// Save the output document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
class ReplaceEvaluatorFindAndHighlight : public IReplacingCallback
{
RTTI_INFO(ReplaceEvaluatorFindAndHighlight, ::System::BaseTypesInfo<IReplacingCallback>);
public:
/// <summary>
/// This method is called by the Aspose.Words find and replace engine for each match.
/// This method highlights the match string, even if it spans multiple runs.
/// </summary>
ReplaceAction Replacing(System::SharedPtr<ReplacingArgs> e) override;
};
ReplaceAction ReplaceEvaluatorFindAndHighlight::Replacing(System::SharedPtr<ReplacingArgs> e)
{
// This is a Run node that contains either the beginning or the complete match.
System::SharedPtr<Node> currentNode = e->get_MatchNode();
// The first (and may be the only) run can contain text before the match,
// In this case it is necessary to split the run.
if (e->get_MatchOffset() > 0)
{
currentNode = SplitRun(System::DynamicCast<Run>(currentNode), e->get_MatchOffset());
}
// This array is used to store all nodes of the match for further highlighting.
std::vector<System::SharedPtr<Run>> runs;
// Find all runs that contain parts of the match string.
int32_t remainingLength = e->get_Match()->get_Value().get_Length();
while ((remainingLength > 0) && (currentNode != nullptr) && (currentNode->GetText().get_Length() <= remainingLength))
{
runs.push_back(System::DynamicCast<Run>(currentNode));
remainingLength = remainingLength - currentNode->GetText().get_Length();
// Select the next Run node.
// Have to loop because there could be other nodes such as BookmarkStart etc.
do
{
currentNode = currentNode->get_NextSibling();
} while ((currentNode != nullptr) && (currentNode->get_NodeType() != NodeType::Run));
}
// Split the last run that contains the match if there is any text left.
if ((currentNode != nullptr) && (remainingLength > 0))
{
auto run = System::DynamicCast<Run>(currentNode);
SplitRun(run, remainingLength);
runs.push_back(run);
}
// Now highlight all runs in the sequence.
for (auto& run : runs)
{
run->get_Font()->set_HighlightColor(System::Drawing::Color::get_Yellow());
}
// Signal to the replace engine to do nothing because we have already done all what we wanted.
return ReplaceAction::Skip;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
/// <summary>
/// Splits text of the specified run into two runs.
/// Inserts the new run just after the specified run.
/// </summary>
System::SharedPtr<Run> SplitRun(const System::SharedPtr<Run>& run, int32_t position)
{
auto afterRun = System::DynamicCast<Run>((System::StaticCast<Node>(run))->Clone(true));
afterRun->set_Text(run->get_Text().Substring(position));
run->set_Text(run->get_Text().Substring(0, position));
run->get_ParentNode()->InsertAfter(afterRun, run);
return afterRun;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Initialize a Document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Use a document builder to add content to the document.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"This is Line 1");
builder->Writeln(u"This is Line 2");
auto findReplaceOptions = System::MakeObject<FindReplaceOptions>();
doc->get_Range()->Replace(u"This is Line 1&pThis is Line 2", u"This is replaced line", findReplaceOptions);
builder->MoveToDocumentEnd();
builder->Write(u"This is Line 1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"This is Line 2");
doc->get_Range()->Replace(u"This is Line 1&mThis is Line 2", u"Page break is replaced with new text.", findReplaceOptions);
auto savePath = dataDir + GetOutputFilePath(u"FindReplaceUsingMetaCharacters.MetaCharactersInSearchPattern.docx");
doc->Save(savePath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Name(u"Arial");
builder->Writeln(u"First section");
builder->Writeln(u" 1st paragraph");
builder->Writeln(u" 2nd paragraph");
builder->Writeln(u"{insert-section}");
builder->Writeln(u"Second section");
builder->Writeln(u" 1st paragraph");
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
options->get_ApplyParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
// Double each paragraph break after word "section", add kind of underline and make it centered.
int32_t count = doc->get_Range()->Replace(u"section&p", u"section&p----------------------&p", options);
// Insert section break instead of custom text tag.
count = doc->get_Range()->Replace(u"{insert-section}", u"&b", options);
auto savePath = dataDir + GetOutputFilePath(u"FindReplaceUsingMetaCharacters.ReplaceTextContaingMetaCharacters.docx");
doc->Save(savePath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
class MyReplaceEvaluator : public IReplacingCallback
{
typedef MyReplaceEvaluator ThisType;
typedef IReplacingCallback BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO(ThisType, ThisTypeBaseTypesInfo)
public:
/// <summary>
/// This is called during a replace operation each time a match is found.
/// This method appends a number to the match string and returns it as a replacement string.
/// </summary>
ReplaceAction Replacing(System::SharedPtr<ReplacingArgs> e) override;
private:
int32_t mMatchNumber = 0;
};
ReplaceAction MyReplaceEvaluator::Replacing(System::SharedPtr<ReplacingArgs> e)
{
e->set_Replacement(e->get_Match()->ToString() + System::Convert::ToString(mMatchNumber));
mMatchNumber++;
return ReplaceAction::Replace;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_FindAndReplace();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Range.ReplaceWithEvaluator.doc");
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
options->set_ReplacingCallback(System::MakeObject<::MyReplaceEvaluator>());
doc->get_Range()->Replace(System::MakeObject<System::Text::RegularExpressions::Regex>(u"[s|m]ad"), u"", options);
System::String outputPath = dataDir + GetOutputFilePath(u"ReplaceWithEvaluator.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_FindAndReplace();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
doc->get_Range()->Replace(System::MakeObject<Regex>(u"[s|m]ad"), u"bad", options);
System::String outputPath = dataDir + GetOutputFilePath(u"ReplaceWithRegex.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_FindAndReplace();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
doc->get_Range()->Replace(u"sad", u"bad", System::MakeObject<FindReplaceOptions>(FindReplaceDirection::Forward));
System::String outputPath = dataDir + GetOutputFilePath(u"ReplaceWithString.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
namespace
{
void InsertWatermarkIntoHeader(const System::SharedPtr<Paragraph>& watermarkPara, const System::SharedPtr<Section>& sect, HeaderFooterType headerType)
{
System::SharedPtr<HeaderFooter> header = sect->get_HeadersFooters()->idx_get(headerType);
if (header == nullptr)
{
// There is no header of the specified type in the current section, create it.
header = System::MakeObject<HeaderFooter>(sect->get_Document(), headerType);
sect->get_HeadersFooters()->Add(header);
}
// Insert a clone of the watermark into the header.
header->AppendChild((System::StaticCast<Node>(watermarkPara))->Clone(true));
}
void InsertWatermarkText(const System::SharedPtr<Document>& doc, const System::String& watermarkText)
{
// Create a watermark shape. This will be a WordArt shape.
// You are free to try other shape types as watermarks.
System::SharedPtr<Shape> watermark = System::MakeObject<Shape>(doc, ShapeType::TextPlainText);
watermark->set_Name(u"WaterMark");
// Set up the text of the watermark.
watermark->get_TextPath()->set_Text(watermarkText);
watermark->get_TextPath()->set_FontFamily(u"Arial");
watermark->set_Width(500);
watermark->set_Height(100);
// Text will be directed from the bottom-left to the top-right corner.
watermark->set_Rotation(-40);
// Remove the following two lines if you need a solid black text.
watermark->get_Fill()->set_Color(System::Drawing::Color::get_Gray());
// Try LightGray to get more Word-style watermark
watermark->set_StrokeColor(System::Drawing::Color::get_Gray());
// Try LightGray to get more Word-style watermark
// Place the watermark in the page center.
watermark->set_RelativeHorizontalPosition(RelativeHorizontalPosition::Page);
watermark->set_RelativeVerticalPosition(RelativeVerticalPosition::Page);
watermark->set_WrapType(WrapType::None);
watermark->set_VerticalAlignment(VerticalAlignment::Center);
watermark->set_HorizontalAlignment(HorizontalAlignment::Center);
// Create a new paragraph and append the watermark to this paragraph.
System::SharedPtr<Paragraph> watermarkPara = System::MakeObject<Paragraph>(doc);
watermarkPara->AppendChild(watermark);
// Insert the watermark into all headers of each document section.
for (System::SharedPtr<Node> sectionNode : System::IterateOver(doc->get_Sections()))
{
System::SharedPtr<Section> sect = System::DynamicCast<Section>(sectionNode);
// There could be up to three different headers in each section, since we want
// The watermark to appear on all pages, insert into all headers.
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType::HeaderPrimary);
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType::HeaderFirst);
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType::HeaderEven);
}
}
}
void AddWatermark()
{
std::cout << "AddWatermark example started." << std::endl;
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithImages();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile.Watermark.doc");
InsertWatermarkText(doc, u"CONFIDENTIAL");
System::String outputPath = dataDir + GetOutputFilePath(u"AddWatermark.doc");
doc->Save(outputPath);
std::cout << "Added watermark to the document successfully." << std::endl << "File saved at " << outputPath.ToUtf8String() << std::endl;
std::cout << "AddWatermark example finished." << std::endl << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithImages();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Image.SampleImages.doc");
System::SharedPtr<NodeCollection> shapes = doc->GetChildNodes(NodeType::Shape, true);
int32_t imageIndex = 0;
for (System::SharedPtr<Shape> shape : System::IterateOver<System::SharedPtr<Shape>>(shapes))
{
if (shape->get_HasImage())
{
System::String imageFileName = System::String::Format(u"Image.ExportImages.{0}_out{1}", imageIndex, FileFormatUtil::ImageTypeToExtension(shape->get_ImageData()->get_ImageType()));
System::String imagePath = dataDir + imageFileName;
shape->get_ImageData()->Save(imagePath);
std::cout << "Image saved at " << imagePath.ToUtf8String() << std::endl;
imageIndex++;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithImages();
// Create a blank documenet.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// The number of pages the document should have.
int32_t numPages = 4;
// The document starts with one section, insert the barcode into this existing section.
InsertBarcodeIntoFooter(builder, doc->get_FirstSection(), 1, HeaderFooterType::FooterPrimary);
for (int32_t i = 1; i < numPages; i++)
{
// Clone the first section and add it into the end of the document.
System::SharedPtr<Section> cloneSection = System::DynamicCast<Section>(System::StaticCast<Node>(doc->get_FirstSection())->Clone(false));
cloneSection->get_PageSetup()->set_SectionStart(SectionStart::NewPage);
doc->AppendChild(cloneSection);
// Insert the barcode and other information into the footer of the section.
InsertBarcodeIntoFooter(builder, cloneSection, i, HeaderFooterType::FooterPrimary);
}
System::String outputPath = dataDir + GetOutputFilePath(u"InsertBarcodeImage.docx");
// Save the document as a DOCX to disk. You can also save this directly to a stream.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void InsertBarcodeIntoFooter(System::SharedPtr<DocumentBuilder> builder, System::SharedPtr<Section> section, int32_t pageId, HeaderFooterType footerType)
{
// Move to the footer type in the specific section.
builder->MoveToSection(section->get_Document()->IndexOf(section));
builder->MoveToHeaderFooter(footerType);
// Insert the barcode, then move to the next line and insert the ID along with the page number.
// Use pageId if you need to insert a different barcode on each page. 0 = First page, 1 = Second page etc.
builder->InsertImage(System::Drawing::Image::FromFile(GetDataDir_WorkingWithImages() + u"Barcode1.png"));
builder->Writeln();
builder->Write(u"1234567890");
builder->InsertField(u"PAGE");
// Create a right aligned tab at the right margin.
double tabPos = section->get_PageSetup()->get_PageWidth() - section->get_PageSetup()->get_RightMargin() - section->get_PageSetup()->get_LeftMargin();
builder->get_CurrentParagraph()->get_ParagraphFormat()->get_TabStops()->Add(System::MakeObject<TabStop>(tabPos, TabAlignment::Right, TabLeader::None));
// Move to the right hand side of the page and insert the page and page total.
builder->Write(ControlChar::Tab());
builder->InsertField(u"PAGE");
builder->Write(u" of ");
builder->InsertField(u"NUMPAGES");
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
namespace
{
void RemoveWatermarkText(const System::SharedPtr<Document>& doc)
{
System::SharedPtr<NodeCollection> headerFooterNodes = doc->GetChildNodes(NodeType::HeaderFooter, true);
for (System::SharedPtr<HeaderFooter> hf : System::IterateOver<System::SharedPtr<HeaderFooter>>(headerFooterNodes))
{
auto shapeNodes = hf->GetChildNodes(NodeType::Shape, true);
for (System::SharedPtr<Shape> shape: System::IterateOver<System::SharedPtr<Shape>>(shapeNodes))
{
if (shape->get_Name().Contains(u"WaterMark"))
{
shape->Remove();
}
}
}
}
}
void RemoveWatermark()
{
std::cout << "RemoveWatermark example started." << std::endl;
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithImages();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"RemoveWatermark.docx");
RemoveWatermarkText(doc);
System::String outputPath = dataDir + GetOutputFilePath(u"RemoveWatermark.docx");
doc->Save(outputPath);
std:: cout << "File saved at " << outputPath.ToUtf8String() << std::endl;
std::cout << "RemoveWatermark example finished." << std::endl << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
ImportFormatMode mode = ImportFormatMode::KeepSourceFormatting;
// Loop through all sections in the source document.
// Section nodes are immediate children of the Document node so we can just enumerate the Document.
for (System::SharedPtr<Section> srcSection : System::IterateOver<System::SharedPtr<Section>>(srcDoc))
{
// Because we are copying a section from one document to another,
// It is required to import the Section node into the destination document.
// This adjusts any document-specific references to styles, lists, etc.
// Importing a node creates a copy of the original node, but the copy
// Is ready to be inserted into the destination document.
System::SharedPtr<Node> dstSection = dstDoc->ImportNode(srcSection, true, mode);
// Now the new section node can be appended to the destination document.
dstDoc->AppendChild(dstSection);
}
System::String outputPath = dataDir + GetOutputFilePath(u"AppendDocumentManually.doc");
// Save the joined document
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
// ExStart
// ExId:AppendDocument_BaseDocument
// ExSummary:Shows how to remove all content from a document before using it as a base to append documents to.
// Use a blank document as the destination document.
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>();
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// The destination document is not actually empty which often causes a blank page to appear before the appended document
// This is due to the base document having an empty section and the new document being started on the next page.
// Remove all content from the destination document before appending.
dstDoc->RemoveAllChildren();
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"BaseDocument.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = ::GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.SourcePageSetup.doc");
// Set the source document to continue straight after the end of the destination document.
// If some page setup settings are different then this may not work and the source document will appear
// On a new page.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
// To ensure this does not happen when the source document has different page setup settings make sure the
// Settings are identical between the last section of the destination document.
// If there are further continuous sections that follow on in the source document then this will need to be
// Repeated for those sections as well.
srcDoc->get_FirstSection()->get_PageSetup()->set_PageWidth(dstDoc->get_LastSection()->get_PageSetup()->get_PageWidth());
srcDoc->get_FirstSection()->get_PageSetup()->set_PageHeight(dstDoc->get_LastSection()->get_PageSetup()->get_PageHeight());
srcDoc->get_FirstSection()->get_PageSetup()->set_Orientation(dstDoc->get_LastSection()->get_PageSetup()->get_Orientation());
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"DifferentPageSetup.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Make the document appear straight after the destination documents content.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
// Append the source document using the original styles found in the source document.
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"JoinContinuous.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Set the appended document to start on a new page.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::NewPage);
// Append the source document using the original styles found in the source document.
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"JoinNewPage.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
// Load the documents to join.
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Keep the formatting from the source document when appending it to the destination document.
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
// Save the joined document to disk.
System::String outputPath = dataDir + GetOutputFilePath(u"KeepSourceFormatting.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.DestinationList.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Set the source document to appear straight after the destination document's content.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
// Iterate through all sections in the source document.
for (System::SharedPtr<Paragraph> para : System::IterateOver<System::SharedPtr<Paragraph>>(srcDoc->GetChildNodes(NodeType::Paragraph, true)))
{
para->get_ParagraphFormat()->set_KeepWithNext(true);
}
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"KeepSourceTogether.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Set the appended document to appear on a new page.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::NewPage);
// Link the headers and footers in the source document to the previous section.
// This will override any headers or footers already found in the source document.
srcDoc->get_FirstSection()->get_HeadersFooters()->LinkToPrevious(true);
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"LinkHeadersFooters.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.DestinationList.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.SourceList.doc");
// Append the content of the document so it flows continuously.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"ListKeepSourceFormatting.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
typedef System::Collections::Generic::Dictionary<int32_t, System::SharedPtr<List>> TListDictionary;
typedef System::Collections::Generic::IDictionary<int32_t, System::SharedPtr<List>> TListIDictionary;
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.DestinationList.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.SourceList.doc");
// Set the source document to continue straight after the end of the destination document.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
// Keep track of the lists that are created.
System::SharedPtr<TListIDictionary> newLists = System::MakeObject<TListDictionary>();
// Iterate through all paragraphs in the document.
for (System::SharedPtr<Paragraph> para : System::IterateOver<System::SharedPtr<Paragraph>>(srcDoc->GetChildNodes(NodeType::Paragraph, true)))
{
if (para->get_IsListItem())
{
int32_t listId = para->get_ListFormat()->get_List()->get_ListId();
// Check if the destination document contains a list with this ID already. If it does then this may
// Cause the two lists to run together. Create a copy of the list in the source document instead.
if (dstDoc->get_Lists()->GetListByListId(listId) != nullptr)
{
System::SharedPtr<List> currentList;
// A newly copied list already exists for this ID, retrieve the stored list and use it on
// The current paragraph.
if (newLists->ContainsKey(listId))
{
currentList = newLists->idx_get(listId);
}
else
{
// Add a copy of this list to the document and store it for later reference.
currentList = srcDoc->get_Lists()->AddCopy(para->get_ListFormat()->get_List());
newLists->Add(listId, currentList);
}
// Set the list of this paragraph to the copied list.
para->get_ListFormat()->set_List(currentList);
}
}
}
// Append the source document to end of the destination document.
dstDoc->AppendDocument(srcDoc, ImportFormatMode::UseDestinationStyles);
System::String outputPath = dataDir + GetOutputFilePath(u"ListUseDestinationStyles.doc");
// Save the combined document to disk.
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Remove the headers and footers from each of the sections in the source document.
for (System::SharedPtr<Section> section : System::IterateOver<System::SharedPtr<Section>>(srcDoc->get_Sections()))
{
section->ClearHeadersFooters();
}
// Even after the headers and footers are cleared from the source document, the "LinkToPrevious" setting
// For HeadersFooters can still be set. This will cause the headers and footers to continue from the destination
// Document. This should set to false to avoid this behavior.
srcDoc->get_FirstSection()->get_HeadersFooters()->LinkToPrevious(false);
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"RemoveSourceHeadersFooters.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Set the appended document to appear on the next page.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::NewPage);
// Restart the page numbering for the document to be appended.
srcDoc->get_FirstSection()->get_PageSetup()->set_RestartPageNumbering(true);
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"RestartPageNumbering.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Unlink the headers and footers in the source document to stop this from continuing the headers and footers
// From the destination document.
srcDoc->get_FirstSection()->get_HeadersFooters()->LinkToPrevious(false);
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
System::String outputPath = dataDir + GetOutputFilePath(u"UnlinkHeadersFooters.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_JoiningAndAppending();
// Load the documents to join.
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>(dataDir + u"TestFile.Destination.doc");
System::SharedPtr<Document> srcDoc = System::MakeObject<Document>(dataDir + u"TestFile.Source.doc");
// Append the source document using the styles of the destination document.
dstDoc->AppendDocument(srcDoc, ImportFormatMode::UseDestinationStyles);
// Save the joined document to disk.
System::String outputPath = dataDir + GetOutputFilePath(u"UseDestinationStyles.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Create a list based on a template.
System::SharedPtr<List> list1 = doc->get_Lists()->Add(ListTemplate::NumberArabicParenthesis);
// Modify the formatting of the list.
list1->get_ListLevels()->idx_get(0)->get_Font()->set_Color(System::Drawing::Color::get_Red());
list1->get_ListLevels()->idx_get(0)->set_Alignment(ListLevelAlignment::Right);
builder->Writeln(u"List 1 starts below:");
// Use the first list in the document for a while.
builder->get_ListFormat()->set_List(list1);
builder->Writeln(u"Item 1");
builder->Writeln(u"Item 2");
builder->get_ListFormat()->RemoveNumbers();
// Now I want to reuse the first list, but need to restart numbering.
// This should be done by creating a copy of the original list formatting.
System::SharedPtr<List> list2 = doc->get_Lists()->AddCopy(list1);
// We can modify the new list in any way. Including setting new start number.
list2->get_ListLevels()->idx_get(0)->set_StartAt(10);
// Use the second list in the document.
builder->Writeln(u"List 2 starts below:");
builder->get_ListFormat()->set_List(list2);
builder->Writeln(u"Item 1");
builder->Writeln(u"Item 2");
builder->get_ListFormat()->RemoveNumbers();
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithList.RestartListNumber.doc");
// Save the document to disk.
builder->get_Document()->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::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));
// There are 9 levels in this list, lets try them all.
for (int32_t i = 0; i < 9; i++)
{
builder->get_ListFormat()->set_ListLevelNumber(i);
builder->Writeln(System::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));
// There are 9 levels in this list, lets try them all.
for (int32_t i = 0; i < 9; i++)
{
builder->get_ListFormat()->set_ListLevelNumber(i);
builder->Writeln(System::String(u"Level ") + i);
}
// This is a way to stop list formatting.
builder->get_ListFormat()->set_List(nullptr);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithList.SpecifyListLevel.doc");
// Save the document to disk.
builder->get_Document()->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto para = System::MakeObject<Paragraph>(doc);
auto section = doc->get_LastSection();
section->get_Body()->AppendChild(para);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto paragraph = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 0, true));
auto children = paragraph->get_ChildNodes();
for (System::SharedPtr<Node> child : System::IterateOver(children))
{
if (System::ObjectExt::Equals(child->get_NodeType(), NodeType::Run))
{
// Say we found the node that we want, do something useful.
auto run = System::DynamicCast<Run>(child);
std::cout << run->get_Text().ToUtf8String() << std::endl;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Create a new empty document. It has one section.
auto doc = System::MakeObject<Document>();
// The section is the first child node of the document.
auto section = doc->get_FirstChild();
// The section's parent node is the document.
std::cout << "Section parent is the document: " << System::ObjectExt::Box<bool>((doc == section->get_ParentNode()))->ToString().ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto paragraph = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 0, true));
auto children = paragraph->get_ChildNodes();
for (int32_t i = 0; i < children->get_Count(); i++)
{
auto child = children->idx_get(i);
// Paragraph may contain children of various types such as runs, shapes and so on.
if (System::ObjectExt::Equals(child->get_NodeType(), NodeType::Run))
{
// Say we found the node that we want, do something useful.
auto run = System::DynamicCast<Run>(child);
std::cout << run->get_Text().ToUtf8String() << std::endl;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Open a file from disk.
auto doc = System::MakeObject<Document>();
// Creating a new node of any type requires a document passed into the constructor.
auto para = System::MakeObject<Paragraph>(doc);
// The new paragraph node does not yet have a parent.
std::cout << "Paragraph has no parent node: " << System::ObjectExt::Box<bool>((para->get_ParentNode() == nullptr))->ToString().ToUtf8String() << std::endl;
// But the paragraph node knows its document.
std::cout << "Both nodes' documents are the same: " << System::ObjectExt::Box<bool>((para->get_Document() == doc))->ToString().ToUtf8String() << std::endl;
// 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.
std::cout << "Paragraph has a parent node: " << System::ObjectExt::Box<bool>((para->get_ParentNode() != nullptr))->ToString().ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void TraverseAllNodes(System::SharedPtr<CompositeNode> parentNode)
{
// This is the most efficient way to loop through immediate children of a node.
for (auto childNode = parentNode->get_FirstChild(); childNode != nullptr; childNode = childNode->get_NextSibling())
{
// Do some useful work.
std::cout << Node::NodeTypeToString(childNode->get_NodeType()).ToUtf8String() << std::endl;
// Recurse into the node if it is a composite node.
if (childNode->get_IsComposite())
{
TraverseAllNodes(System::DynamicCast<CompositeNode>(childNode));
}
}
}
void RecurseAllNodes()
{
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithNode();
// Open a document.
auto doc = System::MakeObject<Document>(dataDir + u"Node.RecurseAllNodes.doc");
// Invoke the recursive function that will walk the tree.
TraverseAllNodes(doc);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto section = doc->get_FirstSection();
// Quick typed access to the Body child node of the Section.
auto body = section->get_Body();
// Quick typed access to all Table child nodes contained in the Body.
auto tables = body->get_Tables();
for (System::SharedPtr<Table> table : System::IterateOver<System::SharedPtr<Table>>(tables))
{
// Quick typed access to the first row of the table.
if (table->get_FirstRow() != nullptr)
{
table->get_FirstRow()->Remove();
}
// Quick typed access to the last row of the table.
if (table->get_LastRow() != nullptr)
{
table->get_LastRow()->Remove();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
// Returns NodeType.Document
NodeType type = doc->get_NodeType();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithRanges();
auto doc = System::MakeObject<Document>(dataDir + u"Document.doc");
doc->get_Sections()->idx_get(0)->get_Range()->Delete();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithRanges();
auto doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::String text = doc->get_Range()->get_Text();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(documentPath);
auto sectionToAdd = System::MakeObject<Section>(doc);
doc->get_Sections()->Add(sectionToAdd);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(documentPath);
doc->get_Sections()->Clear();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(documentPath);
doc->get_Sections()->RemoveAt(0);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithSections();
auto doc = System::MakeObject<Document>(dataDir + u"Section.AppendContent.doc");
// This is the section that we will append and prepend to.
auto section = doc->get_Sections()->idx_get(2);
// This copies content of the 1st section and inserts it at the beginning of the specified section.
auto sectionToPrepend = doc->get_Sections()->idx_get(0);
section->PrependContent(sectionToPrepend);
// This copies content of the 2nd section and inserts it at the end of the specified section.
auto sectionToAppend = doc->get_Sections()->idx_get(1);
section->AppendContent(sectionToAppend);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithSections();
auto doc = System::MakeObject<Document>(dataDir + u"Document.doc");
auto cloneSection = doc->get_Sections()->idx_get(0)->Clone();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithSections();
auto srcDoc = System::MakeObject<Document>(dataDir + u"Document.doc");
auto dstDoc = System::MakeObject<Document>();
auto sourceSection = srcDoc->get_Sections()->idx_get(0);
auto newSection = System::DynamicCast<Section>(dstDoc->ImportNode(sourceSection, true));
dstDoc->get_Sections()->Add(newSection);
System::String outputPath = dataDir + GetOutputFilePath(u"CopySection.doc");
dstDoc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithSections();
auto doc = System::MakeObject<Document>(dataDir + u"Document.doc");
auto section = doc->get_Sections()->idx_get(0);
section->ClearHeadersFooters();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithSections();
auto doc = System::MakeObject<Document>(dataDir + u"Document.doc");
auto section = doc->get_Sections()->idx_get(0);
section->ClearContent();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithSections();
auto doc = System::MakeObject<Document>(dataDir + u"Document.doc");
auto section = doc->get_Sections()->idx_get(0);
section->get_PageSetup()->set_LeftMargin(90);
// 3.17 cm
section->get_PageSetup()->set_RightMargin(90);
// 3.17 cm
section->get_PageSetup()->set_TopMargin(72);
// 2.54 cm
section->get_PageSetup()->set_BottomMargin(72);
// 2.54 cm
section->get_PageSetup()->set_HeaderDistance(35.4);
// 1.25 cm
section->get_PageSetup()->set_FooterDistance(35.4);
// 1.25 cm
section->get_PageSetup()->get_TextColumns()->set_Spacing(35.4);
// 1.25 cm
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
//Free-floating shape insertion.
System::SharedPtr<Shape> shape = builder->InsertShape(ShapeType::TextBox, RelativeHorizontalPosition::Page, 100, RelativeVerticalPosition::Page, 100, 50, 50, WrapType::None);
shape->set_Rotation(30.0);
builder->Writeln();
//Inline shape insertion.
shape = builder->InsertShape(ShapeType::TextBox, 50, 50);
shape->set_Rotation(30.0);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithShapes.InsertShapeUsingDocumentBuilder.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
auto shape = builder->InsertImage(dataDir + u"Test.png");
shape->set_AspectRatioLocked(false);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithShapes.SetAspectRatioLocked.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"LayoutInCell.docx");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Shape> watermark = System::MakeObject<Shape>(doc, ShapeType::TextPlainText);
watermark->set_RelativeHorizontalPosition(RelativeHorizontalPosition::Page);
watermark->set_RelativeVerticalPosition(RelativeVerticalPosition::Page);
watermark->set_IsLayoutInCell(true);
// Display the shape outside of table cell if it will be placed into a cell.
watermark->set_Width(300);
watermark->set_Height(70);
watermark->set_HorizontalAlignment(HorizontalAlignment::Center);
watermark->set_VerticalAlignment(VerticalAlignment::Center);
watermark->set_Rotation(-40);
watermark->get_Fill()->set_Color(System::Drawing::Color::get_Gray());
watermark->set_StrokeColor(System::Drawing::Color::get_Gray());
watermark->get_TextPath()->set_Text(u"watermarkText");
watermark->get_TextPath()->set_FontFamily(u"Arial");
watermark->set_Name(System::String::Format(u"WaterMark_{0}",System::Guid::NewGuid()));
watermark->set_WrapType(WrapType::None);
System::SharedPtr<Run> run = System::DynamicCast_noexcept<Run>(doc->GetChildNodes(NodeType::Run, true)->idx_get(doc->GetChildNodes(NodeType::Run, true)->get_Count() - 1));
builder->MoveTo(run);
builder->InsertNode(watermark);
doc->get_CompatibilityOptions()->OptimizeFor(MsWordVersion::Word2010);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithShapes.SetShapeLayoutInCell.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<CustomXmlPart> xmlPart = doc->get_CustomXmlParts()->Add(System::Guid::NewGuid().ToString(u"B"), u"<root><text>Hello, World!</text></root>");
System::SharedPtr<StructuredDocumentTag> sdt = System::MakeObject<StructuredDocumentTag>(doc, SdtType::PlainText, MarkupLevel::Block);
doc->get_FirstSection()->get_Body()->AppendChild(sdt);
sdt->get_XmlMapping()->SetMapping(xmlPart, u"/root[1]/text[1]", u"");
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithSDT.BindSDTtoCustomXmlPart.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"input.docx");
System::SharedPtr<StructuredDocumentTag> sdt = System::DynamicCast<StructuredDocumentTag>(doc->GetChild(NodeType::StructuredDocumentTag, 0, true));
sdt->Clear();
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithSDT.ClearContentsControl.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"input.docx");
System::SharedPtr<StructuredDocumentTag> sdt = System::DynamicCast<StructuredDocumentTag>(doc->GetChild(NodeType::StructuredDocumentTag, 0, true));
sdt->set_Color(System::Drawing::Color::get_Red());
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithSDT.SetContentControlColor.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
// Retrieve the style used for the first level of the TOC and change the formatting of the style.
doc->get_Styles()->idx_get(StyleIdentifier::Toc1)->get_Font()->set_Bold(true);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithStyles();
// Open the document.
auto doc = System::MakeObject<Document>(dataDir + u"Document.TableOfContents.doc");
// Iterate through all paragraphs in the document
for (System::SharedPtr<Paragraph> para : System::IterateOver<System::SharedPtr<Paragraph>>(doc->GetChildNodes(NodeType::Paragraph, true)))
{
// Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
if (para->get_ParagraphFormat()->get_Style()->get_StyleIdentifier() >= StyleIdentifier::Toc1 && para->get_ParagraphFormat()->get_Style()->get_StyleIdentifier() <= StyleIdentifier::Toc9)
{
// Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
auto tab = para->get_ParagraphFormat()->get_TabStops()->idx_get(0);
// Remove the old tab from the collection.
para->get_ParagraphFormat()->get_TabStops()->RemoveByPosition(tab->get_Position());
// Insert a new tab using the same properties but at a modified position.
// We could also change the separators used (dots) by passing a different Leader type
para->get_ParagraphFormat()->get_TabStops()->Add(tab->get_Position() - 50, tab->get_Alignment(), tab->get_Leader());
}
}
System::String outputPath = dataDir + GetOutputFilePath(u"ChangeTOCTabStops.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithStyles();
// Open the document.
auto doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
// Define style names as they are specified in the Word document.
const System::String paraStyle = u"Heading 1";
const System::String runStyle = u"Intense Emphasis";
// Collect paragraphs with defined styles.
// Show the number of collected paragraphs and display the text of this paragraphs.
auto paragraphs = ParagraphsByStyleName(doc, paraStyle);
std::cout << "Paragraphs with \"" << paraStyle.ToUtf8String() << "\" styles (" << paragraphs.size() << "):" << std::endl;
for (System::SharedPtr<Paragraph> paragraph : paragraphs)
{
std::cout << paragraph->ToString(SaveFormat::Text).ToUtf8String();
}
std::cout << std::endl;
// Collect runs with defined styles.
// Show the number of collected runs and display the text of this runs.
auto runs = RunsByStyleName(doc, runStyle);
std::cout << "Runs with \"" << runStyle.ToUtf8String() << "\" styles (" << runs.size() << "):" << std::endl;
for (System::SharedPtr<Run> run : runs)
{
std::cout << run->get_Range()->get_Text().ToUtf8String() << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::SharedPtr<Paragraph>> ParagraphsByStyleName(System::SharedPtr<Document> doc, System::String const &styleName)
{
// Create an array to collect paragraphs of the specified style.
std::vector<System::SharedPtr<Paragraph>> paragraphsWithStyle;
// Get all paragraphs from the document.
auto paragraphs = doc->GetChildNodes(NodeType::Paragraph, true);
// Look through all paragraphs to find those with the specified style.
for (System::SharedPtr<Paragraph> paragraph : System::IterateOver<System::SharedPtr<Paragraph>>(paragraphs))
{
if (paragraph->get_ParagraphFormat()->get_Style()->get_Name() == styleName)
{
paragraphsWithStyle.push_back(paragraph);
}
}
return paragraphsWithStyle;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::SharedPtr<Run>> RunsByStyleName(System::SharedPtr<Document> doc, System::String const &styleName)
{
// Create an array to collect runs of the specified style.
std::vector<System::SharedPtr<Run>> runsWithStyle;
// Get all runs from the document.
auto runs = doc->GetChildNodes(NodeType::Run, true);
// Look through all runs to find those with the specified style.
for (System::SharedPtr<Run> run : System::IterateOver<System::SharedPtr<Run>>(runs))
{
if (run->get_Font()->get_Style()->get_Name() == styleName)
{
runsWithStyle.push_back(run);
}
}
return runsWithStyle;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
auto paraStyle = builder->get_Document()->get_Styles()->Add(StyleType::Paragraph, u"MyParaStyle");
paraStyle->get_Font()->set_Bold(false);
paraStyle->get_Font()->set_Size(8);
paraStyle->get_Font()->set_Name(u"Arial");
// Append text with "Heading 1" style.
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Write(u"Heading 1");
builder->InsertStyleSeparator();
// Append text with another style.
builder->get_ParagraphFormat()->set_StyleName(paraStyle->get_Name());
builder->Write(u"This is text with some other formatting ");
System::String outputPath = dataDir + GetOutputFilePath(u"InsertStyleSeparator.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Get the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Get the second column in the table.
auto column = System::MakeObject<Column>(table, 0);
// Print the plain text of the column to the screen.
std::cout << column->ToTxt().ToUtf8String() << std::endl;
// Create a new column to the left of this column.
// This is the same as using the "Insert Column Before" command in Microsoft Word.
auto newColumn = column->InsertColumnBefore();
// Add some text to each of the column cells.
auto columnCells = newColumn->GetColumnCells();
for (System::SharedPtr<Cell> cell : newColumn->GetColumnCells())
{
cell->get_FirstParagraph()->AppendChild(System::MakeObject<Run>(doc, System::String(u"Column Text ") + newColumn->IndexOf(cell)));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Get the second table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 1, true));
// Get the third column from the table and remove it.
auto column = System::MakeObject<Column>(table, 2);
column->Remove();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.EmptyTable.doc");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Align the table to the center of the page.
table->set_Alignment(TableAlignment::Center);
// Clear any existing borders from the table.
table->ClearBorders();
// Set a green border around the table but not inside.
table->SetBorder(BorderType::Left, LineStyle::Single, 1.5, System::Drawing::Color::get_Green(), true);
table->SetBorder(BorderType::Right, LineStyle::Single, 1.5, System::Drawing::Color::get_Green(), true);
table->SetBorder(BorderType::Top, LineStyle::Single, 1.5, System::Drawing::Color::get_Green(), true);
table->SetBorder(BorderType::Bottom, LineStyle::Single, 1.5, System::Drawing::Color::get_Green(), true);
// Fill the cells with a light green solid color.
table->SetShading(TextureIndex::TextureSolid, System::Drawing::Color::get_LightGreen(), System::Drawing::Color::Empty);
System::String outputPath = dataDir + GetOutputFilePath(u"ApplyFormatting.ApplyOutlineBorder.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
auto table = builder->StartTable();
builder->InsertCell();
// Set the row formatting
auto rowFormat = builder->get_RowFormat();
rowFormat->set_Height(100);
rowFormat->set_HeightRule(HeightRule::Exactly);
// These formatting properties are set on the table and are applied to all rows in the table.
table->set_LeftPadding(30);
table->set_RightPadding(30);
table->set_TopPadding(30);
table->set_BottomPadding(30);
builder->Writeln(u"I'm a wonderful formatted row.");
builder->EndRow();
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"ApplyFormatting.ApplyRowFormatting.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.EmptyTable.doc");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Clear any existing borders from the table.
table->ClearBorders();
// Set a green border around and inside the table.
table->SetBorders(LineStyle::Single, 1.5, System::Drawing::Color::get_Green());
System::String outputPath = dataDir + GetOutputFilePath(u"ApplyFormatting.BuildTableWithBordersEnabled.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
auto table = builder->StartTable();
builder->InsertCell();
// Set the borders for the entire table.
table->SetBorders(LineStyle::Single, 2.0, System::Drawing::Color::get_Black());
// Set the cell shading for this cell.
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_Red());
builder->Writeln(u"Cell #1");
builder->InsertCell();
// Specify a different cell shading for the second cell.
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_Green());
builder->Writeln(u"Cell #2");
// End this row.
builder->EndRow();
// Clear the cell formatting from previous operations.
builder->get_CellFormat()->ClearFormatting();
// Create the second row.
builder->InsertCell();
// Create larger borders for the first cell of this row. This will be different.
// Compared to the borders set for the table.
builder->get_CellFormat()->get_Borders()->get_Left()->set_LineWidth(4.0);
builder->get_CellFormat()->get_Borders()->get_Right()->set_LineWidth(4.0);
builder->get_CellFormat()->get_Borders()->get_Top()->set_LineWidth(4.0);
builder->get_CellFormat()->get_Borders()->get_Bottom()->set_LineWidth(4.0);
builder->Writeln(u"Cell #3");
builder->InsertCell();
// Clear the cell formatting from the previous cell.
builder->get_CellFormat()->ClearFormatting();
builder->Writeln(u"Cell #4");
// Save finished document.
System::String outputPath = dataDir + GetOutputFilePath(u"ApplyFormatting.FormatTableAndCellWithDifferentBorders.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.EmptyTable.doc");
std::cout << "Get distance between table left, right, bottom, top and the surrounding text." << std::endl;
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
std::cout << table->get_DistanceTop() << std::endl;
std::cout << table->get_DistanceBottom() << std::endl;
std::cout << table->get_DistanceRight() << std::endl;
std::cout << table->get_DistanceLeft() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.Document.doc");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Retrieve the first cell in the table.
auto firstCell = table->get_FirstRow()->get_FirstCell();
// Modify some cell level properties.
firstCell->get_CellFormat()->set_Width(30);
// In points
firstCell->get_CellFormat()->set_Orientation(TextOrientation::Downward);
firstCell->get_CellFormat()->get_Shading()->set_ForegroundPatternColor(System::Drawing::Color::get_LightGreen());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.Document.doc");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Retrieve the first row in the table.
auto firstRow = table->get_FirstRow();
// Modify some row level properties.
firstRow->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::None);
firstRow->get_RowFormat()->set_HeightRule(HeightRule::Auto);
firstRow->get_RowFormat()->set_AllowBreakAcrossPages(true);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
builder->StartTable();
builder->InsertCell();
//Sets the amount of space (in points) to add to the left/top/right/bottom of the contents of cell.
builder->get_CellFormat()->SetPaddings(30, 50, 30, 50);
builder->Writeln(u"I'm a wonderful formatted cell.");
builder->EndRow();
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"ApplyFormatting.SetCellPadding.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.Document.doc");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
table->set_Title(u"Test title");
table->set_Description(u"Test description");
auto options = System::MakeObject<DocSaveOptions>();
doc->get_CompatibilityOptions()->OptimizeFor(MsWordVersion::Word2016);
System::String outputPath = dataDir + GetOutputFilePath(u"ApplyFormatting.SetTableTitleandDescription.docx");
// Save the document to disk.
doc->Save(outputPath, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
auto table = builder->StartTable();
// We must insert at least one row first before setting any table formatting.
builder->InsertCell();
// Set the table style used based of the unique style identifier.
// Note that not all table styles are available when saving as .doc format.
table->set_StyleIdentifier(StyleIdentifier::MediumShading1Accent1);
// Apply which features should be formatted by the style.
table->set_StyleOptions(TableStyleOptions::FirstColumn | TableStyleOptions::RowBands | TableStyleOptions::FirstRow);
table->AutoFit(AutoFitBehavior::AutoFitToContents);
// Continue with building the table as normal.
builder->Writeln(u"Item");
builder->get_CellFormat()->set_RightPadding(40);
builder->InsertCell();
builder->Writeln(u"Quantity (kg)");
builder->EndRow();
builder->InsertCell();
builder->Writeln(u"Apples");
builder->InsertCell();
builder->Writeln(u"20");
builder->EndRow();
builder->InsertCell();
builder->Writeln(u"Bananas");
builder->InsertCell();
builder->Writeln(u"40");
builder->EndRow();
builder->InsertCell();
builder->Writeln(u"Carrots");
builder->InsertCell();
builder->Writeln(u"50");
builder->EndRow();
System::String outputPath = dataDir + GetOutputFilePath(u"ApplyStyle.BuildTableWithStyle.docx");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.TableStyle.docx");
// Get the first cell of the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
auto firstCell = table->get_FirstRow()->get_FirstCell();
// First print the color of the cell shading. This should be empty as the current shading
// Is stored in the table style.
System::Drawing::Color cellShadingBefore = firstCell->get_CellFormat()->get_Shading()->get_BackgroundPatternColor();
std::cout << "Cell shading before style expansion: " << cellShadingBefore.ToString().ToUtf8String() << std::endl;
// Expand table style formatting to direct formatting.
doc->ExpandTableStylesToDirectFormatting();
// Now print the cell shading after expanding table styles. A blue background pattern color
// Should have been applied from the table style.
System::Drawing::Color cellShadingAfter = firstCell->get_CellFormat()->get_Shading()->get_BackgroundPatternColor();
std::cout << "Cell shading after style expansion: " << cellShadingAfter.ToString().ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithTables();
auto doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Auto fit the table to the cell contents
table->AutoFit(AutoFitBehavior::AutoFitToContents);
System::String outputPath = dataDir + GetOutputFilePath(u"AutoFitTableToContents.doc");
// Save the document to disk.
doc->Save(outputPath);
auto firstTable = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
Debug::Assert(firstTable->get_PreferredWidth()->get_Type() == PreferredWidthType::Auto, u"PreferredWidth type is not auto");
Debug::Assert(firstTable->get_FirstRow()->get_FirstCell()->get_CellFormat()->get_PreferredWidth()->get_Type() == PreferredWidthType::Auto, u"PrefferedWidth on cell is not auto");
Debug::Assert(firstTable->get_FirstRow()->get_FirstCell()->get_CellFormat()->get_PreferredWidth()->get_Value() == 0, u"PreferredWidth value is not 0");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithTables();
auto doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Disable autofitting on this table.
table->AutoFit(AutoFitBehavior::FixedColumnWidths);
System::String outputPath = dataDir + GetOutputFilePath(u"AutoFitTableToFixedColumnWidths.doc");
// Save the document to disk.
doc->Save(outputPath);
auto firstTable = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
Debug::Assert(firstTable->get_PreferredWidth()->get_Type() == PreferredWidthType::Auto, u"PreferredWidth type is not auto");
Debug::Assert(firstTable->get_PreferredWidth()->get_Value() == 0, u"PreferredWidth value is not 0");
Debug::Assert(firstTable->get_FirstRow()->get_FirstCell()->get_CellFormat()->get_Width() == 69.2, u"Cell width is not correct.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithTables();
// Open the document
auto doc = System::MakeObject<Document>(dataDir + u"TestFile.doc");
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Autofit the first table to the page width.
table->AutoFit(AutoFitBehavior::AutoFitToWindow);
System::String outputPath = dataDir + GetOutputFilePath(u"AutoFitTableToWindow.doc");
// Save the document to disk.
doc->Save(outputPath);
auto firstTable = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
Debug::Assert(firstTable->get_PreferredWidth()->get_Type() == PreferredWidthType::Percent, u"PreferredWidth type is not percent");
Debug::Assert(firstTable->get_PreferredWidth()->get_Value() == 100, u"PreferredWidth value is different than 100");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.SimpleTable.doc");
// Retrieve the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Create a clone of the table.
auto tableClone = System::DynamicCast<Table>((System::StaticCast<Node>(table))->Clone(true));
// Insert the cloned table into the document after the original
table->get_ParentNode()->InsertAfter(tableClone, table);
// Insert an empty paragraph between the two tables or else they will be combined into one
// Upon save. This has to do with document validation.
table->get_ParentNode()->InsertAfter(System::MakeObject<Paragraph>(doc), table);
System::String outputPath = dataDir + GetOutputFilePath(u"CloneTable.CloneCompleteTable.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.SimpleTable.doc");
// Retrieve the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Clone the last row in the table.
auto clonedRow = System::DynamicCast<Row>((System::StaticCast<Node>(table->get_LastRow()))->Clone(true));
// Remove all content from the cloned row's cells. This makes the row ready for
// New content to be inserted into.
for (System::SharedPtr<Cell> cell : System::IterateOver<System::SharedPtr<Cell>>(clonedRow->get_Cells()))
{
cell->RemoveAllChildren();
}
// Add the row to the end of the table.
table->AppendChild(clonedRow);
System::String outputPath = dataDir + GetOutputFilePath(u"CloneTable.CloneLastRow.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(documentPath);
// Get the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// The range text will include control characters such as "\a" for a cell.
// You can call ToString and pass SaveFormat.Text on the desired node to find the plain text content.
// Print the plain text range of the table to the screen.
std::cout << "Contents of the table: " << std::endl << table->get_Range()->get_Text().ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Print the contents of the second row to the screen.
std::cout << "Contents of the row: " << std::endl << table->get_Rows()->idx_get(1)->get_Range()->get_Text().ToUtf8String() << std::endl;
// Print the contents of the last cell in the table to the screen.
std::cout << "Contents of the cell: " << std::endl << table->get_LastRow()->get_LastCell()->get_Range()->get_Text().ToUtf8String() << std::endl;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(documentPath);
// Get the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Replace any instances of our string in the entire table.
table->get_Range()->Replace(u"Carrots", u"Eggs", System::MakeObject<FindReplaceOptions>(FindReplaceDirection::Forward));
// Replace any instances of our string in the last cell of the table only.
table->get_LastRow()->get_LastCell()->get_Range()->Replace(u"50", u"20", System::MakeObject<FindReplaceOptions>(FindReplaceDirection::Forward));
System::String outputPath = GetDataDir_WorkingWithTables() + GetOutputFilePath(u"ExtractOrReplaceText.ReplaceText.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
int32_t cellIndex = row->IndexOf(row->get_Cells()->idx_get(4));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
int32_t rowIndex = table->IndexOf(table->get_LastRow());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Get the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
auto allTables = doc->GetChildNodes(NodeType::Table, true);
int32_t tableIndex = allTables->IndexOf(table);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithTables();
auto doc = System::MakeObject<Document>();
// We start by creating the table object. Note how we must pass the document object
// To the constructor of each node. This is because every node we create must belong
// To some document.
auto table = System::MakeObject<Table>(doc);
// Add the table to the document.
doc->get_FirstSection()->get_Body()->AppendChild(table);
// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// To ensure that the specified node is valid, in this case a valid table should have at least one
// Row and one cell, therefore this method creates them for us.
// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// If we were creating a table inside an algorthim for example.
auto row = System::MakeObject<Row>(doc);
row->get_RowFormat()->set_AllowBreakAcrossPages(true);
table->AppendChild(row);
// We can now apply any auto fit settings.
table->AutoFit(AutoFitBehavior::FixedColumnWidths);
// Create a cell and add it to the row
auto cell = System::MakeObject<Cell>(doc);
cell->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_LightBlue());
cell->get_CellFormat()->set_Width(80);
// Add a paragraph to the cell as well as a new run with some text.
cell->AppendChild(System::MakeObject<Paragraph>(doc));
cell->get_FirstParagraph()->AppendChild(System::MakeObject<Run>(doc, u"Row 1, Cell 1 Text"));
// Add the cell to the row.
row->AppendChild(cell);
// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row->AppendChild((System::StaticCast<Node>(cell))->Clone(false));
row->get_LastCell()->AppendChild(System::MakeObject<Paragraph>(doc));
row->get_LastCell()->get_FirstParagraph()->AppendChild(System::MakeObject<Run>(doc, u"Row 1, Cell 2 Text"));
System::String outputPath = dataDir + GetOutputFilePath(u"InsertTableDirectly.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
auto table = builder->StartTable();
// Make the header row.
builder->InsertCell();
// Set the left indent for the table. Table wide formatting must be applied after
// At least one row is present in the table.
table->set_LeftIndent(20.0);
// Set height and define the height rule for the header row.
builder->get_RowFormat()->set_Height(40.0);
builder->get_RowFormat()->set_HeightRule(HeightRule::AtLeast);
// Some special features for the header row.
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::FromArgb(198, 217, 241));
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_Font()->set_Size(16);
builder->get_Font()->set_Name(u"Arial");
builder->get_Font()->set_Bold(true);
builder->get_CellFormat()->set_Width(100.0);
builder->Write(u"Header Row,\n Cell 1");
// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder->InsertCell();
builder->Write(u"Header Row,\n Cell 2");
builder->InsertCell();
builder->get_CellFormat()->set_Width(200.0);
builder->Write(u"Header Row,\n Cell 3");
builder->EndRow();
// Set features for the other rows and cells.
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_White());
builder->get_CellFormat()->set_Width(100.0);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
// Reset height and define a different height rule for table body
builder->get_RowFormat()->set_Height(30.0);
builder->get_RowFormat()->set_HeightRule(HeightRule::Auto);
builder->InsertCell();
// Reset font formatting.
builder->get_Font()->set_Size(12);
builder->get_Font()->set_Bold(false);
// Build the other cells.
builder->Write(u"Row 1, Cell 1 Content");
builder->InsertCell();
builder->Write(u"Row 1, Cell 2 Content");
builder->InsertCell();
builder->get_CellFormat()->set_Width(200.0);
builder->Write(u"Row 1, Cell 3 Content");
builder->EndRow();
builder->InsertCell();
builder->get_CellFormat()->set_Width(100.0);
builder->Write(u"Row 2, Cell 1 Content");
builder->InsertCell();
builder->Write(u"Row 2, Cell 2 Content");
builder->InsertCell();
builder->get_CellFormat()->set_Width(200.0);
builder->Write(u"Row 2, Cell 3 Content.");
builder->EndRow();
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertTableUsingDocumentBuilder.FormattedTable.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Build the outer table.
auto cell = builder->InsertCell();
builder->Writeln(u"Outer Table Cell 1");
builder->InsertCell();
builder->Writeln(u"Outer Table Cell 2");
// This call is important in order to create a nested table within the first table
// Without this call the cells inserted below will be appended to the outer table.
builder->EndTable();
// Move to the first cell of the outer table.
builder->MoveTo(cell->get_FirstParagraph());
// Build the inner table.
builder->InsertCell();
builder->Writeln(u"Inner Table Cell 1");
builder->InsertCell();
builder->Writeln(u"Inner Table Cell 2");
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertTableUsingDocumentBuilder.NestedTable.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// We call this method to start building the table.
builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, Cell 1 Content.");
// Build the second cell
builder->InsertCell();
builder->Write(u"Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder->EndRow();
// Build the first cell of the second row.
builder->InsertCell();
builder->Write(u"Row 2, Cell 1 Content");
// Build the second cell.
builder->InsertCell();
builder->Write(u"Row 2, Cell 2 Content.");
builder->EndRow();
// Signal that we have finished building the table.
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"InsertTableUsingDocumentBuilder.SimpleTable.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Load the document.
auto doc = System::MakeObject<Document>(dataDir + u"Table.Document.doc");
// Get the first and second table in the document.
// The rows from the second table will be appended to the end of the first table.
auto firstTable = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
auto secondTable = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 1, true));
// Append all rows from the current table to the next.
// Due to the design of tables even tables with different cell count and widths can be joined into one table.
while (secondTable->get_HasChildNodes())
{
firstTable->get_Rows()->Add(secondTable->get_FirstRow());
}
// Remove the empty table container.
secondTable->Remove();
System::String outputPath = dataDir + GetOutputFilePath(u"JoiningAndSplittingTable.CombineRows.doc");
// Save the finished document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Load the document.
auto doc = System::MakeObject<Document>(dataDir + u"Table.Document.doc");
// Get the first table in the document.
auto firstTable = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// We will split the table at the third row (inclusive).
auto row = firstTable->get_Rows()->idx_get(2);
// Create a new container for the split table.
auto table = System::DynamicCast<Table>((System::StaticCast<Node>(firstTable))->Clone(false));
// Insert the container after the original.
firstTable->get_ParentNode()->InsertAfter(table, firstTable);
// Add a buffer paragraph to ensure the tables stay apart.
firstTable->get_ParentNode()->InsertAfter(System::MakeObject<Paragraph>(doc), firstTable);
System::SharedPtr<Row> currentRow;
do
{
currentRow = firstTable->get_LastRow();
table->PrependChild(currentRow);
} while (currentRow != row);
System::String outputPath = dataDir + GetOutputFilePath(u"JoiningAndSplittingTable.SplitTable.doc");
// Save the finished document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.TableAcrossPage.doc");
// Retrieve the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// To keep a table from breaking across a page we need to enable KeepWithNext
// For every paragraph in the table except for the last paragraphs in the last
// Row of the table.
for (System::SharedPtr<Cell> cell : System::IterateOver<System::SharedPtr<Cell>>(table->GetChildNodes(NodeType::Cell, true)))
{
// Call this method if table's cell is created on the fly
// Newly created cell does not have paragraph inside
cell->EnsureMinimum();
for (System::SharedPtr<Paragraph> para : System::IterateOver<System::SharedPtr<Paragraph>>(cell->get_Paragraphs()))
{
if (!(cell->get_ParentRow()->get_IsLastRow() && para->get_IsEndOfCell()))
{
para->get_ParagraphFormat()->set_KeepWithNext(true);
}
}
}
System::String outputPath = dataDir + GetOutputFilePath(u"KeepTablesAndRowsBreaking.KeepTableTogether.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.TableAcrossPage.doc");
// Retrieve the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
// Disable breaking across pages for all rows in the table.
for (System::SharedPtr<Row> row : System::IterateOver<System::SharedPtr<Row>>(table->get_Rows()))
{
row->get_RowFormat()->set_AllowBreakAcrossPages(false);
}
System::String outputPath = dataDir + GetOutputFilePath(u"KeepTablesAndRowsBreaking.RowFormatDisableBreakAcrossPages.doc");
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.MergedCells.doc");
// Retrieve the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
for (System::SharedPtr<Row> row : System::IterateOver<System::SharedPtr<Row>>(table->get_Rows()))
{
for (System::SharedPtr<Cell> cell : System::IterateOver<System::SharedPtr<Cell>>(row->get_Cells()))
{
std::cout << PrintCellMergeType(cell).ToUtf8String() << std::endl;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
class CellInfo : public System::Object
{
typedef CellInfo ThisType;
typedef System::Object BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
public:
CellInfo(int32_t colSpan, int32_t rowSpan) : mColSpan(colSpan), mRowSpan(rowSpan) {}
int32_t GetColSpan() { return mColSpan; }
int32_t GetRowSpan() { return mRowSpan; }
private:
int32_t mColSpan;
int32_t mRowSpan;
};
RTTI_INFO_IMPL_HASH(1673797985u, CellInfo, ThisTypeBaseTypesInfo);
typedef System::Collections::Generic::List<System::SharedPtr<CellInfo>> TCellsInfo;
typedef System::SharedPtr<TCellsInfo> TCellsInfoPtr;
class RowInfo : public System::Object
{
typedef RowInfo ThisType;
typedef System::Object BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
public:
RowInfo() : mCells(System::MakeObject<TCellsInfo>()) {}
TCellsInfoPtr GetCells() { return mCells; }
protected:
System::Object::shared_members_type GetSharedMembers() override;
private:
TCellsInfoPtr mCells;
};
RTTI_INFO_IMPL_HASH(2224295735u, RowInfo, ThisTypeBaseTypesInfo);
System::Object::shared_members_type RowInfo::GetSharedMembers()
{
auto result = System::Object::GetSharedMembers();
result.Add("RowInfo::mCells", this->mCells);
return std::move(result);
}
typedef System::Collections::Generic::List<System::SharedPtr<RowInfo>> TRowsInfo;
typedef System::SharedPtr<TRowsInfo> TRowsInfoPtr;
class TableInfo : public System::Object
{
typedef TableInfo ThisType;
typedef System::Object BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
public:
TableInfo() : mRows(System::MakeObject<TRowsInfo>()) {}
TRowsInfoPtr GetRows() { return mRows; }
protected:
System::Object::shared_members_type GetSharedMembers() override;
private:
TRowsInfoPtr mRows;
};
RTTI_INFO_IMPL_HASH(2175561643u, TableInfo, ThisTypeBaseTypesInfo);
System::Object::shared_members_type TableInfo::GetSharedMembers()
{
auto result = System::Object::GetSharedMembers();
result.Add("TableInfo::mRows", this->mRows);
return std::move(result);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertCell();
builder->get_CellFormat()->set_HorizontalMerge(CellMerge::First);
builder->Write(u"Text in merged cells.");
builder->InsertCell();
// This cell is merged to the previous and should be empty.
builder->get_CellFormat()->set_HorizontalMerge(CellMerge::Previous);
builder->EndRow();
builder->InsertCell();
builder->get_CellFormat()->set_HorizontalMerge(CellMerge::None);
builder->Write(u"Text in one cell.");
builder->InsertCell();
builder->Write(u"Text in another cell.");
builder->EndRow();
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"MergedCells.HorizontalMerge.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Open the document
auto doc = System::MakeObject<Document>(dataDir + u"Table.Document.doc");
// Retrieve the first table in the body of the first section.
auto table = doc->get_FirstSection()->get_Body()->get_Tables()->idx_get(0);
// We want to merge the range of cells found inbetween these two cells.
auto cellStartRange = table->get_Rows()->idx_get(2)->get_Cells()->idx_get(2);
auto cellEndRange = table->get_Rows()->idx_get(3)->get_Cells()->idx_get(3);
// Merge all the cells between the two specified cells into one.
MergeCells(cellStartRange, cellEndRange);
System::String outputPath = dataDir + GetOutputFilePath(u"MergedCells.MergeCellRange.doc");
// Save the document.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
void MergeCells(System::SharedPtr<Cell> startCell, System::SharedPtr<Cell> endCell)
{
auto parentTable = startCell->get_ParentRow()->get_ParentTable();
// Find the row and cell indices for the start and end cell.
System::Drawing::Point startCellPos(startCell->get_ParentRow()->IndexOf(startCell), parentTable->IndexOf(startCell->get_ParentRow()));
System::Drawing::Point endCellPos(endCell->get_ParentRow()->IndexOf(endCell), parentTable->IndexOf(endCell->get_ParentRow()));
// Create the range of cells to be merged based off these indices. Inverse each index if the end cell if before the start cell.
System::Drawing::Rectangle mergeRange(System::Math::Min(startCellPos.get_X(), endCellPos.get_X()),
System::Math::Min(startCellPos.get_Y(), endCellPos.get_Y()),
System::Math::Abs(endCellPos.get_X() - startCellPos.get_X()) + 1,
System::Math::Abs(endCellPos.get_Y() - startCellPos.get_Y()) + 1);
for (System::SharedPtr<Row> row : System::IterateOver<System::SharedPtr<Row>>(parentTable->get_Rows()))
{
for (System::SharedPtr<Cell> cell : System::IterateOver<System::SharedPtr<Cell>>(row->get_Cells()))
{
System::Drawing::Point currentPos(row->IndexOf(cell), parentTable->IndexOf(row));
// Check if the current cell is inside our merge range then merge it.
if (mergeRange.Contains(currentPos))
{
if (currentPos.get_X() == mergeRange.get_X())
{
cell->get_CellFormat()->set_HorizontalMerge(CellMerge::First);
}
else
{
cell->get_CellFormat()->set_HorizontalMerge(CellMerge::Previous);
}
if (currentPos.get_Y() == mergeRange.get_Y())
{
cell->get_CellFormat()->set_VerticalMerge(CellMerge::First);
}
else
{
cell->get_CellFormat()->set_VerticalMerge(CellMerge::Previous);
}
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::String PrintCellMergeType(System::SharedPtr<Cell> cell)
{
bool isHorizontallyMerged = cell->get_CellFormat()->get_HorizontalMerge() != CellMerge::None;
bool isVerticallyMerged = cell->get_CellFormat()->get_VerticalMerge() != CellMerge::None;
System::String cellLocation = System::String::Format(u"R{0}, C{1}", cell->get_ParentRow()->get_ParentTable()->IndexOf(cell->get_ParentRow()) + 1, cell->get_ParentRow()->IndexOf(cell) + 1);
if (isHorizontallyMerged && isVerticallyMerged)
{
return System::String::Format(u"The cell at {0} is both horizontally and vertically merged", cellLocation);
}
if (isHorizontallyMerged)
{
return System::String::Format(u"The cell at {0} is horizontally merged.", cellLocation);
}
if (isVerticallyMerged)
{
return System::String::Format(u"The cell at {0} is vertically merged", cellLocation);
}
return System::String::Format(u"The cell at {0} is not merged", cellLocation);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertCell();
builder->get_CellFormat()->set_VerticalMerge(CellMerge::First);
builder->Write(u"Text in merged cells.");
builder->InsertCell();
builder->get_CellFormat()->set_VerticalMerge(CellMerge::None);
builder->Write(u"Text in one cell");
builder->EndRow();
builder->InsertCell();
// This cell is vertically merged to the cell above and should be empty.
builder->get_CellFormat()->set_VerticalMerge(CellMerge::Previous);
builder->InsertCell();
builder->get_CellFormat()->set_VerticalMerge(CellMerge::None);
builder->Write(u"Text in another cell");
builder->EndRow();
builder->EndTable();
System::String outputPath = dataDir + GetOutputFilePath(u"MergedCells.VerticalMerge.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithTables();
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
auto table = builder->StartTable();
builder->get_RowFormat()->set_HeadingFormat(true);
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->set_Width(100);
builder->InsertCell();
builder->Writeln(u"Heading row 1");
builder->EndRow();
builder->InsertCell();
builder->Writeln(u"Heading row 2");
builder->EndRow();
builder->get_CellFormat()->set_Width(50);
builder->get_ParagraphFormat()->ClearFormatting();
// Insert some content so the table is long enough to continue onto the next page.
for (int32_t i = 0; i < 50; i++)
{
builder->InsertCell();
builder->get_RowFormat()->set_HeadingFormat(false);
builder->Write(u"Column 1 Text");
builder->InsertCell();
builder->Write(u"Column 2 Text");
builder->EndRow();
}
System::String outputPath = dataDir + GetOutputFilePath(u"RepeatRowsOnSubsequentPages.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
table->set_AllowAutoFit(true);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a table with a width that takes up half the page width.
auto table = builder->StartTable();
// Insert a few cells
builder->InsertCell();
table->set_PreferredWidth(PreferredWidth::FromPercent(50));
builder->Writeln(u"Cell #1");
builder->InsertCell();
builder->Writeln(u"Cell #2");
builder->InsertCell();
builder->Writeln(u"Cell #3");
System::String outputPath = dataDir + GetOutputFilePath(u"SpecifyHeightAndWidth.AutoFitToPageWidth.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.SimpleTable.doc");
// Retrieve the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
table->set_AllowAutoFit(true);
auto firstCell = table->get_FirstRow()->get_FirstCell();
PreferredWidthType type = firstCell->get_CellFormat()->get_PreferredWidth()->get_Type();
double value = firstCell->get_CellFormat()->get_PreferredWidth()->get_Value();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a table row made up of three cells which have different preferred widths.
auto table = builder->StartTable();
// Insert an absolute sized cell.
builder->InsertCell();
builder->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPoints(40));
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_LightYellow());
builder->Writeln(u"Cell at 40 points width");
// Insert a relative (percent) sized cell.
builder->InsertCell();
builder->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(20));
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_LightBlue());
builder->Writeln(u"Cell at 20% width");
// Insert a auto sized cell.
builder->InsertCell();
builder->get_CellFormat()->set_PreferredWidth(PreferredWidth::Auto());
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_LightGreen());
builder->Writeln(u"Cell automatically sized. The size of this cell is calculated from the table preferred width.");
builder->Writeln(u"In this case the cell will fill up the rest of the available space.");
System::String outputPath = dataDir + GetOutputFilePath(u"SpecifyHeightAndWidth.SetPreferredWidthSettings.doc");
// Save the document to disk.
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"FloatingTablePosition.doc");
for (System::SharedPtr<Table> table : System::IterateOver<System::SharedPtr<Table>>(doc->get_FirstSection()->get_Body()->get_Tables()))
{
// If table is floating type then print its positioning properties.
if (table->get_TextWrapping() == TextWrapping::Around)
{
std::cout << System::ObjectExt::Box<RelativeHorizontalPosition>(table->get_HorizontalAnchor())->ToString().ToUtf8String() << std::endl;
std::cout << System::ObjectExt::Box<RelativeVerticalPosition>(table->get_VerticalAnchor())->ToString().ToUtf8String() << std::endl;
std::cout << table->get_AbsoluteHorizontalDistance() << std::endl;
std::cout << table->get_AbsoluteVerticalDistance() << std::endl;
std::cout << table->get_AllowOverlap() << std::endl;
std::cout << ".............................." << std::endl;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(dataDir + u"Table.Document.doc");
// Retrieve the first table in the document.
auto table = System::DynamicCast<Table>(doc->GetChild(NodeType::Table, 0, true));
if (table->get_TextWrapping() == TextWrapping::Around)
{
std::cout << System::ObjectExt::Box<HorizontalAlignment>(table->get_RelativeHorizontalAlignment())->ToString().ToUtf8String() << std::endl;
std::cout << System::ObjectExt::Box<VerticalAlignment>(table->get_RelativeVerticalAlignment())->ToString().ToUtf8String() << std::endl;
}
else
{
std::cout << System::ObjectExt::Box<TableAlignment>(table->get_Alignment())->ToString().ToUtf8String() << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir);
System::SharedPtr<Theme> theme = doc->get_Theme();
// Major (Headings) font for Latin characters.
std::cout << theme->get_MajorFonts()->get_Latin().ToUtf8String() << std::endl;
// Minor (Body) font for EastAsian characters.
std::cout << theme->get_MinorFonts()->get_EastAsian().ToUtf8String() << std::endl;
// Color for theme color Accent 1.
std::cout << System::ObjectExt::Box<System::Drawing::Color>(theme->get_Colors()->get_Accent1())->ToString().ToUtf8String();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir);
System::SharedPtr<Theme> theme = doc->get_Theme();
// Set Times New Roman font as Body theme font for Latin Character.
theme->get_MinorFonts()->set_Latin(u"Times New Roman");
// Set Color.Gold for theme color Hyperlink.
theme->get_Colors()->set_Hyperlink(System::Drawing::Color::get_Gold());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<License> license = System::MakeObject<License>();
// This line attempts to set a license from several locations relative to the executable and Aspose.Words.dll.
// You can also use the additional overload to load a license from a stream, this is useful for instance when the
// license is stored as an embedded resource
try
{
license->SetLicense(u"Aspose.Words.Cpp.lic");
std::cout << "License set successfully." << std::endl;
}
catch (System::Exception& e)
{
// We do not ship any license with this example, visit the Aspose site to obtain either a temporary or permanent license.
std::cout << "There was an error setting the license: " << e.get_Message().ToUtf8String() << std::endl;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<License> license = System::MakeObject<License>();
try
{
// Initializes a license from a stream
System::SharedPtr<System::IO::MemoryStream> stream = System::MakeObject<System::IO::MemoryStream>(System::IO::File::ReadAllBytes(u"Aspose.Words.Cpp.lic"));
license->SetLicense(stream);
std::cout << "License set successfully." << std::endl;
}
catch (System::Exception& e)
{
// We do not ship any license with this example, visit the Aspose site to obtain either a temporary or permanent license.
std::cout << "There was an error setting the license: " << e.get_Message().ToUtf8String() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment