Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This Gist contains code snippets from examples of Aspose.Words for C++.
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
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);
// 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"Document.EpubConversion.doc");
// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// How the output document is saved.
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>();
// Specify the desired encoding.
saveOptions->set_Encoding(System::Text::Encoding::get_UTF8());
// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions->set_DocumentSplitCriteria(DocumentSplitCriteria::HeadingParagraph);
// Specify that we want to export document properties.
saveOptions->set_ExportDocumentProperties(true);
// Specify that we want to save in EPUB format.
saveOptions->set_SaveFormat(SaveFormat::Epub);
// Export the document as an EPUB file.
doc->Save(dataDir + GetOutputFilePath(u"ConvertDocumentToEPUB.epub"), saveOptions);
// 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");
System::SharedPtr<HtmlSaveOptions> options = System::MakeObject<HtmlSaveOptions>();
// HtmlSaveOptions.ExportRoundtripInformation property specifies
// Whether to write the roundtrip information when saving to HTML, MHTML or EPUB.
// Default value is true for HTML and false for MHTML and EPUB.
options->set_ExportRoundtripInformation(true);
doc->Save(dataDir + GetOutputFilePath(u"ConvertDocumentToHtmlWithRoundtrip.html"), options);
// 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 (docx).docx");
System::SharedPtr<PclSaveOptions> saveOptions = System::MakeObject<PclSaveOptions>();
saveOptions->set_SaveFormat(SaveFormat::Pcl);
saveOptions->set_RasterizeTransformedElements(false);
// Export the document as an PCL file.
doc->Save(dataDir + GetOutputFilePath(u"ConvertDocumentToPCL.pcl"), saveOptions);
// 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;
}
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Template.doc");
System::SharedPtr<PdfSaveOptions> saveOptions = System::MakeObject<PdfSaveOptions>();
saveOptions->set_DisplayDocTitle(true);
System::String outputPath = dataDir + GetOutputFilePath(u"Doc2Pdf.DisplayDocTitleInWindowTitlebar.pdf");
// Save the document in PDF format.
doc->Save(outputPath, saveOptions);
// The path to the documents directory.
System::String dataDir = GetDataDir_QuickStart();
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Template.doc");
System::String outputPath = dataDir + GetOutputFilePath(u"Doc2Pdf.pdf");
// Save the document in PDF format.
doc->Save(outputPath);
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>();
saveOptions->set_ExportFontResources(true);
saveOptions->set_ExportFontsAsBase64(true);
System::String outputPath = dataDir + GetOutputFilePath(u"ExportFontsAsBase64.html");
doc->Save(outputPath, saveOptions);
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
System::String fileName = u"Document.doc";
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + fileName);
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>();
saveOptions->set_CssStyleSheetType(CssStyleSheetType::External);
saveOptions->set_ExportFontResources(true);
saveOptions->set_ResourceFolder(dataDir + u"\\ExportResourcesUsingHtmlSaveOptions.Resources");
saveOptions->set_ResourceFolderAlias(u"http://example.com/resources");
System::String outputPath = dataDir + GetOutputFilePath(u"ExportResourcesUsingHtmlSaveOptions.html");
doc->Save(outputPath, saveOptions);
// 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);
System::SharedPtr<LoadOptions> lo = System::MakeObject<LoadOptions>();
lo->set_ConvertShapeToOfficeMath(true);
// Specify load option to use previous default behaviour i.e. convert math shapes to office math ojects on loading stage.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"OfficeMath.docx", lo);
System::String outputPath = dataDir + GetOutputFilePath(u"Load_Options.ConvertShapeToOfficeMath.docx");
//Save the document into DOCX
doc->Save(outputPath, Aspose::Words::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);
System::SharedPtr<FileFormatInfo> info = FileFormatUtil::DetectFileFormat(dataDir + u"encrypted.odt");
std::cout << info->get_IsEncrypted() << std::endl;
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
System::SharedPtr<HtmlLoadOptions> lo = System::MakeObject<HtmlLoadOptions>();
lo->set_PreferredControlType(HtmlControlType::StructuredDocumentTag);
//Load the HTML document
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"input.html", lo);
//Save the HTML document into DOCX
doc->Save(dataDir + GetOutputFilePath(u"LoadAndSaveHtmlFormFieldAsContentControlInDOCX.docx"), 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);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Write(u"Here is an SVG image: ");
builder->InsertHtml(u"<svg height='210' width='500'><polygon points='100,10 40,198 190,78 10,78 160,198' style='fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;' /></svg> ");
System::SharedPtr<HtmlSaveOptions> options = System::MakeObject<HtmlSaveOptions>();
options->set_MetafileFormat(HtmlMetafileFormat::Svg);
System::String outputPath = dataDir + GetOutputFilePath(u"SaveDocWithHtmlSaveOptions.ImportExportSVGinHTML.html");
doc->Save(outputPath, options);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.docx");
System::SharedPtr<HtmlSaveOptions> options = System::MakeObject<HtmlSaveOptions>();
options->set_MetafileFormat(HtmlMetafileFormat::EmfOrWmf);
System::String outputPath = dataDir + GetOutputFilePath(u"SaveDocWithHtmlSaveOptions.SaveHtmlWithMetafileFormat.html");
doc->Save(outputPath, options);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.docx");
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>();
saveOptions->set_CssStyleSheetType(CssStyleSheetType::External);
saveOptions->set_CssClassNamePrefix(u"pfx_");
System::String outputPath = dataDir + GetOutputFilePath(u"SaveDocWithHtmlSaveOptions.SetCssClassNamePrefix.html");
doc->Save(outputPath, saveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"CidUrls.docx");
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>(SaveFormat::Mhtml);
saveOptions->set_PrettyFormat(true);
saveOptions->set_ExportCidUrlsForMhtmlResources(true);
saveOptions->set_SaveFormat(SaveFormat::Mhtml);
System::String outputPath = dataDir + GetOutputFilePath(u"SaveDocWithHtmlSaveOptions.SetExportCidUrlsForMhtmlResources.mhtml");
doc->Save(outputPath, saveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Test File (docx).docx");
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>(SaveFormat::Html);
saveOptions->set_PrettyFormat(true);
saveOptions->set_ResolveFontNames(true);
System::String outputPath = dataDir + GetOutputFilePath(u"SaveDocWithHtmlSaveOptions.SetResolveFontNames.html");
doc->Save(outputPath, saveOptions);
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Test File (doc).doc");
System::SharedPtr<HtmlFixedSaveOptions> options = System::MakeObject<HtmlFixedSaveOptions>();
options->set_UseTargetMachineFonts(true);
System::String outputPath = dataDir + GetOutputFilePath(u"SaveOptionsHtmlFixed.UseFontFromTargetMachine.html");
// Save the document to disk.
doc->Save(outputPath, options);
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Test File (doc).doc");
System::SharedPtr<HtmlFixedSaveOptions> options = System::MakeObject<HtmlFixedSaveOptions>();
//Setting this property to true restores the old behavior (separate files) for compatibility with legacy code.
//Default value is false.
//All CSS rules are written into single file "styles.css
options->set_SaveFontFaceCssSeparately(false);
System::String outputPath = dataDir + GetOutputFilePath(u"SaveOptionsHtmlFixed.WriteAllCSSrulesinSingleFile.html");
// Save the document to disk.
doc->Save(outputPath, options);
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TestFile RenderShape.docx");
// This is the directory we want the exported images to be saved to.
System::String imagesDir = System::IO::Path::Combine(dataDir, u"SpecifySaveOption.Images");
// The folder specified needs to exist and should be empty.
if (System::IO::Directory::Exists(imagesDir))
{
System::IO::Directory::Delete(imagesDir, true);
}
System::IO::Directory::CreateDirectory_(imagesDir);
// Set an option to export form fields as plain text, not as HTML input elements.
System::SharedPtr<HtmlSaveOptions> options = System::MakeObject<HtmlSaveOptions>(SaveFormat::Html);
options->set_ExportTextInputFormFieldAsText(true);
options->set_ImagesFolder(imagesDir);
System::String outputPath = dataDir + GetOutputFilePath(u"SpecifySaveOption.html");
doc->Save(outputPath, options);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::SharedPtr<OoxmlSaveOptions> so = System::MakeObject<OoxmlSaveOptions>(SaveFormat::FlatOpc);
so->set_KeepLegacyControlChars(true);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithOoxml.KeepLegacyControlChars.docx");
// Save the document to disk.
doc->Save(outputPath, so);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
// Set Word2016 version for document
doc->get_CompatibilityOptions()->OptimizeFor(MsWordVersion::Word2016);
//Set the Strict compliance level.
System::SharedPtr<OoxmlSaveOptions> ooxmlSaveOptions = System::MakeObject<OoxmlSaveOptions>();
ooxmlSaveOptions->set_Compliance(OoxmlCompliance::Iso29500_2008_Strict);
ooxmlSaveOptions->set_SaveFormat(SaveFormat::Docx);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithOoxml.SetOOXMLCompliance.docx");
doc->Save(outputPath, ooxmlSaveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::SharedPtr<OoxmlSaveOptions> ooxmlSaveOptions = System::MakeObject<OoxmlSaveOptions>();
ooxmlSaveOptions->set_UpdateLastSavedTimeProperty(true);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithOoxml.UpdateLastSavedTimeProperty.docx");
// Save the document to disk.
doc->Save(outputPath, ooxmlSaveOptions);
// 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);
System::SharedPtr<Document> doc1 = System::MakeObject<Document>(dataDir + u"Input.docx");
doc1->Save(dataDir + GetOutputFilePath(u"WorkingWithTxt.DefaultLevelForListIndentation1.txt"));
System::SharedPtr<Document> doc2 = System::MakeObject<Document>(dataDir + u"Input.docx");
System::SharedPtr<TxtSaveOptions> options = System::MakeObject<TxtSaveOptions>();
doc2->Save(dataDir + GetOutputFilePath(u"WorkingWithTxt.DefaultLevelForListIndentation2.txt"), options);
// 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);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"TxtExportHeadersFootersMode.docx");
System::SharedPtr<TxtSaveOptions> options = System::MakeObject<TxtSaveOptions>();
options->set_SaveFormat(Aspose::Words::SaveFormat::Text);
// All headers and footers are placed at the very end of the output document.
options->set_ExportHeadersFootersMode(Aspose::Words::Saving::TxtExportHeadersFootersMode::AllAtEnd);
doc->Save(dataDir + GetOutputFilePath(u"WorkingWithTxt.ExportHeadersFootersMode.AllAtEnd.txt"), options);
// Only primary headers and footers are exported at the beginning and end of each section.
options->set_ExportHeadersFootersMode(Aspose::Words::Saving::TxtExportHeadersFootersMode::PrimaryOnly);
doc->Save(dataDir + GetOutputFilePath(u"WorkingWithTxt.ExportHeadersFootersMode.PrimaryOnly.txt"), options);
// No headers and footers are exported.
options->set_ExportHeadersFootersMode(Aspose::Words::Saving::TxtExportHeadersFootersMode::None);
doc->Save(dataDir + GetOutputFilePath(u"WorkingWithTxt.ExportHeadersFootersMode.None.txt"), options);
// 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);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Input.docx");
System::SharedPtr<TxtSaveOptions> options = System::MakeObject<TxtSaveOptions>();
options->get_ListIndentation()->set_Count(3);
options->get_ListIndentation()->set_Character(u' ');
doc->Save(dataDir + GetOutputFilePath(u"WorkingWithTxt.UseSpaceCharacterPerLevelForListIndentation.txt"), options);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Input.docx");
System::SharedPtr<TxtSaveOptions> options = System::MakeObject<TxtSaveOptions>();
options->get_ListIndentation()->set_Count(1);
options->get_ListIndentation()->set_Character(u'\t');
doc->Save(dataDir + GetOutputFilePath(u"WorkingWithTxt.UseTabCharacterPerLevelForListIndentation.txt"), options);
// 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);
System::String fileName = u"MailMerge.CleanupPunctuationMarks.docx";
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + fileName);
doc->get_MailMerge()->set_CleanupOptions(MailMergeCleanupOptions::RemoveEmptyParagraphs);
doc->get_MailMerge()->set_CleanupParagraphsWithPunctuationMarks(false);
typedef System::SharedPtr<System::Object> TObjectPtr;
doc->get_MailMerge()->Execute(System::MakeArray<System::String>({u"field1", u"field2"}),
System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::String>(u""), System::ObjectExt::Box<System::String>(u"")}));
System::String outputPath = dataDir + GetOutputFilePath(u"MailMergeCleanUp.CleanupParagraphsWithPunctuationMarks.docx");
// Save the output document to disk.
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);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Add chart with default data.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Line, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
chart->get_Title()->set_Text(u"Data Labels With Different Number Format");
// Delete default generated series.
chart->get_Series()->Clear();
// Add new series
System::SharedPtr<ChartSeries> series0 = chart->get_Series()->Add(u"AW Series 0", System::MakeArray<System::String>({u"AW0", u"AW1", u"AW2"}), System::MakeArray<double>({2.5, 1.5, 3.5}));
// Add DataLabel to the first point of the first series.
System::SharedPtr<ChartDataLabel> chartDataLabel0 = series0->get_DataLabels()->Add(0);
chartDataLabel0->set_ShowValue(true);
// Set currency format code.
chartDataLabel0->get_NumberFormat()->set_FormatCode(u"\"$\"#,##0.00");
System::SharedPtr<ChartDataLabel> chartDataLabel1 = series0->get_DataLabels()->Add(1);
chartDataLabel1->set_ShowValue(true);
// Set date format code.
chartDataLabel1->get_NumberFormat()->set_FormatCode(u"d/mm/yyyy");
System::SharedPtr<ChartDataLabel> chartDataLabel2 = series0->get_DataLabels()->Add(2);
chartDataLabel2->set_ShowValue(true);
// Set percentage format code.
chartDataLabel2->get_NumberFormat()->set_FormatCode(u"0.00%");
// Or you can set format code to be linked to a source cell,
// in this case NumberFormat will be reset to general and inherited from a source cell.
chartDataLabel2->get_NumberFormat()->set_IsLinkedToSource(true);
System::String outputPath = dataDir + GetOutputFilePath(u"ChartNumberFormat.docx");
doc->Save(outputPath);
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithCharts();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Line, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Determines whether the title shall be shown for this chart. Default is true.
chart->get_Title()->set_Show(true);
// Setting chart Title.
chart->get_Title()->set_Text(u"Sample Line Chart Title");
// Determines whether other chart elements shall be allowed to overlap title.
chart->get_Title()->set_Overlay(false);
// Please note if null or empty value is specified as title text, auto generated title will be shown.
// Determines how legend shall be shown for this chart.
chart->get_Legend()->set_Position(LegendPosition::Left);
chart->get_Legend()->set_Overlay(true);
System::String outputPath = dataDir + GetOutputFilePath(u"CreateChartUsingShape.docx");
doc->Save(outputPath);
// Get chart series collection.
System::SharedPtr<ChartSeriesCollection> seriesColl = chart->get_Series();
// Check series count.
std::cout << seriesColl->get_Count() << std::endl;
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert Column chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Column, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Use this overload to add series to any type of Bar, Column, Line and Surface charts.
chart->get_Series()->Add(u"AW Series 1", System::MakeArray<System::String>({u"AW Category 1", u"AW Category 2"}), System::MakeArray<double>({1, 2}));
System::String outputPath = dataDir + GetOutputFilePath(u"CreateColumnChart.InsertColumnChart.doc");
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Add chart with default data. You can specify different chart types and sizes.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Column, 432, 252);
// Chart property of Shape contains all chart related options.
System::SharedPtr<Chart> chart = shape->get_Chart();
// Get chart series collection.
System::SharedPtr<ChartSeriesCollection> seriesColl = chart->get_Series();
// Check series count.
std::cout << seriesColl->get_Count() << std::endl;
// Delete default generated series.
seriesColl->Clear();
// Create category names array, in this example we have two categories.
System::ArrayPtr<System::String> categories = System::MakeArray<System::String>({u"AW Category 1", u"AW Category 2"});
// Adding new series. Please note, data arrays must not be empty and arrays must be the same size.
seriesColl->Add(u"AW Series 1", categories, System::MakeArray<double>({1, 2}));
seriesColl->Add(u"AW Series 2", categories, System::MakeArray<double>({3, 4}));
seriesColl->Add(u"AW Series 3", categories, System::MakeArray<double>({5, 6}));
seriesColl->Add(u"AW Series 4", categories, System::MakeArray<double>({7, 8}));
seriesColl->Add(u"AW Series 5", categories, System::MakeArray<double>({9, 10}));
System::String outputPath = dataDir + GetOutputFilePath(u"CreateColumnChart.InsertSimpleColumnChart.doc");
doc->Save(outputPath);
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithCharts();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert Area chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Area, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Use this overload to add series to any type of Area, Radar and Stock charts.
chart->get_Series()->Add(u"AW Series 1",
System::MakeArray<System::DateTime>({System::DateTime(2002, 5, 1), System::DateTime(2002, 6, 1), System::DateTime(2002, 7, 1), System::DateTime(2002, 8, 1), System::DateTime(2002, 9, 1)}),
System::MakeArray<double>({32, 32, 28, 12, 15}));
System::String outputPath = dataDir + GetOutputFilePath(u"InsertAreaChart.docx");
doc->Save(outputPath);
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithCharts();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert Bubble chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Bubble, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Use this overload to add series to any type of Bubble charts.
chart->get_Series()->Add(u"AW Series 1",
System::MakeArray<double>({0.7, 1.8, 2.6}),
System::MakeArray<double>({2.7, 3.2, 0.8}),
System::MakeArray<double>({10, 4, 8}));
System::String outputPath = dataDir + GetOutputFilePath(u"InsertBubbleChart.docx");
doc->Save(outputPath);
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithCharts();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert Scatter chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Scatter, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Use this overload to add series to any type of Scatter charts.
chart->get_Series()->Add(u"AW Series 1", System::MakeArray<double>({0.7, 1.8, 2.6}), System::MakeArray<double>({2.7, 3.2, 0.8}));
System::String outputPath = dataDir + GetOutputFilePath(u"InsertScatterChart.docx");
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Area, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Clear demo data.
chart->get_Series()->Clear();
// Fill data.
System::ArrayPtr<System::DateTime> dates = System::MakeArray<System::DateTime>({System::DateTime(2002, 1, 1),
System::DateTime(2002, 6, 1),
System::DateTime(2002, 7, 1),
System::DateTime(2002, 8, 1),
System::DateTime(2002, 9, 1)});
chart->get_Series()->Add(u"AW Series 1", dates, System::MakeArray<double>({640, 320, 280, 120, 150}));
System::SharedPtr<ChartAxis> xAxis = chart->get_AxisX();
System::SharedPtr<ChartAxis> yAxis = chart->get_AxisY();
// Change the X axis to be category instead of date, so all the points will be put with equal interval on the X axis.
xAxis->set_CategoryType(AxisCategoryType::Category);
// Define X axis properties.
xAxis->set_Crosses(AxisCrosses::Custom);
xAxis->set_CrossesAt(3);
// measured in display units of the Y axis (hundreds)
xAxis->set_ReverseOrder(true);
xAxis->set_MajorTickMark(AxisTickMark::Cross);
xAxis->set_MinorTickMark(AxisTickMark::Outside);
xAxis->set_TickLabelOffset(200);
// Define Y axis properties.
yAxis->set_TickLabelPosition(AxisTickLabelPosition::High);
yAxis->set_MajorUnit(100);
yAxis->set_MinorUnit(50);
yAxis->get_DisplayUnit()->set_Unit(AxisBuiltInUnit::Hundreds);
yAxis->get_Scaling()->set_Minimum(System::MakeObject<AxisBound>(100));
yAxis->get_Scaling()->set_Maximum(System::MakeObject<AxisBound>(700));
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithChartAxis.DefineXYAxisProperties.docx");
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Column, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Clear demo data.
chart->get_Series()->Clear();
// Fill data.
chart->get_Series()->Add(u"AW Series 1",
System::MakeArray<System::String>({u"Item 1", u"Item 2", u"Item 3", u"Item 4", u"Item 5"}),
System::MakeArray<double>({1.2, 0.3, 2.1, 2.9, 4.2}));
// Hide the Y axis.
chart->get_AxisY()->set_Hidden(true);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithChartAxis.HideChartAxis.docx");
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Column, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Clear demo data.
chart->get_Series()->Clear();
// Fill data.
chart->get_Series()->Add(u"AW Series 1",
System::MakeArray<System::String>({u"Item 1", u"Item 2", u"Item 3", u"Item 4", u"Item 5"}),
System::MakeArray<double>({1.2, 0.3, 2.1, 2.9, 4.2}));
chart->get_AxisY()->get_Scaling()->set_Minimum(System::MakeObject<AxisBound>(0));
chart->get_AxisY()->get_Scaling()->set_Maximum(System::MakeObject<AxisBound>(6));
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithChartAxis.SetBoundsOfAxis.docx");
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Column, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Clear demo data.
chart->get_Series()->Clear();
// Fill data.
System::ArrayPtr<System::DateTime> dates = System::MakeArray<System::DateTime>({System::DateTime(2017, 11, 6),
System::DateTime(2017, 11, 9),
System::DateTime(2017, 11, 15),
System::DateTime(2017, 11, 21),
System::DateTime(2017, 11, 25),
System::DateTime(2017, 11, 29)});
chart->get_Series()->Add(u"AW Series 1", dates, System::MakeArray<double>({1.2, 0.3, 2.1, 2.9, 4.2, 5.3}));
// Set X axis bounds.
System::SharedPtr<ChartAxis> xAxis = chart->get_AxisX();
xAxis->get_Scaling()->set_Minimum(System::MakeObject<AxisBound>((System::DateTime(2017, 11, 5)).ToOADate()));
xAxis->get_Scaling()->set_Maximum(System::MakeObject<AxisBound>((System::DateTime(2017, 12, 3)).ToOADate()));
// Set major units to a week and minor units to a day.
xAxis->set_MajorUnit(7);
xAxis->set_MinorUnit(1);
xAxis->set_MajorTickMark(AxisTickMark::Cross);
xAxis->set_MinorTickMark(AxisTickMark::Outside);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithChartAxis.SetDateTimeValuesToAxis.docx");
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Column, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Clear demo data.
chart->get_Series()->Clear();
// Fill data.
chart->get_Series()->Add(u"AW Series 1",
System::MakeArray<System::String>({u"Item 1", u"Item 2", u"Item 3", u"Item 4", u"Item 5"}),
System::MakeArray<double>({1.2, 0.3, 2.1, 2.9, 4.2}));
chart->get_AxisX()->set_TickLabelSpacing(2);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithChartAxis.SetIntervalUnitBetweenLabelsOnAxis.docx");
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert chart.
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Column, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Clear demo data.
chart->get_Series()->Clear();
// Fill data.
chart->get_Series()->Add(u"AW Series 1",
System::MakeArray<System::String>({u"Item 1", u"Item 2", u"Item 3", u"Item 4", u"Item 5"}),
System::MakeArray<double>({1900000, 850000, 2100000, 600000, 1500000}));
// Set number format.
chart->get_AxisY()->get_NumberFormat()->set_FormatCode(u"#,##0");
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithChartAxis.SetNumberFormatForAxis.docx");
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.docx");
System::SharedPtr<Shape> shape = System::DynamicCast<Shape>(doc->GetChild(NodeType::Shape, 0, true));
System::SharedPtr<ChartAxis> axis = shape->get_Chart()->get_AxisX();
//This property has effect only for multi-line labels.
axis->set_TickLabelAlignment(ParagraphAlignment::Right);
doc->Save(dataDir + GetOutputFilePath(u"WorkingWithChartAxis.TickMultiLineLabelAlignment.docx"));
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithCharts();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Bar, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Get first series.
System::SharedPtr<ChartSeries> series0 = shape->get_Chart()->get_Series()->idx_get(0);
System::SharedPtr<ChartDataLabelCollection> dataLabelCollection = series0->get_DataLabels();
// Add data label to the first and second point of the first series.
System::SharedPtr<ChartDataLabel> chartDataLabel00 = dataLabelCollection->Add(0);
System::SharedPtr<ChartDataLabel> chartDataLabel01 = dataLabelCollection->Add(1);
// Set properties.
chartDataLabel00->set_ShowLegendKey(true);
// By default, when you add data labels to the data points in a pie chart, leader lines are displayed for data labels that are
// Positioned far outside the end of data points. Leader lines create a visual connection between a data label and its
// Corresponding data point.
chartDataLabel00->set_ShowLeaderLines(true);
chartDataLabel00->set_ShowCategoryName(false);
chartDataLabel00->set_ShowPercentage(false);
chartDataLabel00->set_ShowSeriesName(true);
chartDataLabel00->set_ShowValue(true);
chartDataLabel00->set_Separator(u"/");
chartDataLabel01->set_ShowValue(true);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkWithChartDataLabel.docx");
doc->Save(outputPath);
// The path to the documents directory.
System::String dataDir = GetDataDir_WorkingWithCharts();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Line, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
// Get first series.
System::SharedPtr<ChartSeries> series0 = shape->get_Chart()->get_Series()->idx_get(0);
// Get second series.
System::SharedPtr<ChartSeries> series1 = shape->get_Chart()->get_Series()->idx_get(1);
System::SharedPtr<ChartDataPointCollection> dataPointCollection = series0->get_DataPoints();
// Add data point to the first and second point of the first series.
System::SharedPtr<ChartDataPoint> dataPoint00 = dataPointCollection->Add(0);
System::SharedPtr<ChartDataPoint> dataPoint01 = dataPointCollection->Add(1);
// Set explosion.
dataPoint00->set_Explosion(50);
// Set marker symbol and size.
dataPoint00->get_Marker()->set_Symbol(MarkerSymbol::Circle);
dataPoint00->get_Marker()->set_Size(15);
dataPoint01->get_Marker()->set_Symbol(MarkerSymbol::Diamond);
dataPoint01->get_Marker()->set_Size(20);
// Add data point to the third point of the second series.
System::SharedPtr<ChartDataPoint> dataPoint12 = series1->get_DataPoints()->Add(2);
dataPoint12->set_InvertIfNegative(true);
dataPoint12->get_Marker()->set_Symbol(Aspose::Words::Drawing::Charts::MarkerSymbol::Star);
dataPoint12->get_Marker()->set_Size(20);
System::String outputPath = dataDir + GetOutputFilePath(u"WorkWithSingleChartDataPoint.docx");
doc->Save(outputPath);
// Specifies whether by default the parent element shall inverts its colors if the value is negative.
series0->set_InvertIfNegative(true);
// Set default marker symbol and size.
series0->get_Marker()->set_Symbol(MarkerSymbol::Circle);
series0->get_Marker()->set_Size(15);
series1->get_Marker()->set_Symbol(MarkerSymbol::Star);
series1->get_Marker()->set_Size(10);
// Get first series.
System::SharedPtr<ChartSeries> series0 = shape->get_Chart()->get_Series()->idx_get(0);
// Get second series.
System::SharedPtr<ChartSeries> series1 = shape->get_Chart()->get_Series()->idx_get(1);
// Change first series name.
series0->set_Name(u"My Name1");
// Change second series name.
series1->set_Name(u"My Name2");
// You can also specify whether the line connecting the points on the chart shall be smoothed using Catmull-Rom splines.
series0->set_Smooth(true);
series1->set_Smooth(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_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();
}
}
}
// 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");
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));
System::SharedPtr<Node> currentNode = commentStart;
bool isRemoving = true;
while (currentNode != nullptr && isRemoving)
{
if (currentNode->get_NodeType() == NodeType::CommentRangeEnd)
{
isRemoving = false;
}
System::SharedPtr<Node> nextNode = currentNode->NextPreOrder(doc);
currentNode->Remove();
currentNode = nextNode;
}
System::String outputPath = dataDir + GetOutputFilePath(u"RemoveRegionText.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);
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