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++.
// The path to the documents directory.
System::String dataDir = GetInputDataDir_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);
}
System::ArrayPtr<System::String> fileList = System::IO::Directory::GetFiles(dataDir);
// Loop through all found files.
for (System::String const &fileName: fileList)
{
// 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.
System::SharedPtr<FileFormatInfo> 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;
}
}
}
// Check the file format and move the file to the appropriate folder.
System::SharedPtr<FileFormatInfo> 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;
}
System::ArrayPtr<System::String> fileList = System::IO::Directory::GetFiles(dataDir);
// The path to the documents directory.
System::String dataDir = GetInputDataDir_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);
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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(outputDataDir + u"ConvertDocumentToEPUB.ConvertDocumentToEPUB.epub", saveOptions);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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(outputDataDir + u"ConvertDocumentToHtmlWithRoundtrip.html", options);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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(outputDataDir + u"ConvertDocumentToPCL.pcl", saveOptions);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"CreateDocument.docx";
// Save the document to disk.
doc->Save(outputPath);
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
// The path to the document which is to be processed.
System::String filePath = inputDataDir + 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>(inputDataDir + u"Template.doc");
System::SharedPtr<PdfSaveOptions> saveOptions = System::MakeObject<PdfSaveOptions>();
saveOptions->set_DisplayDocTitle(true);
System::String outputPath = outputDataDir + u"Doc2Pdf.DisplayDocTitleInWindowTitlebar.pdf";
// Save the document in PDF format.
doc->Save(outputPath, saveOptions);
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Template.doc");
System::String outputPath = outputDataDir + u"Doc2Pdf.Doc2PdfImpl.pdf";
// Save the document in PDF format.
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>();
saveOptions->set_ExportFontResources(true);
saveOptions->set_ExportFontsAsBase64(true);
System::String outputPath = outputDataDir + u"ExportFontsAsBase64.html";
doc->Save(outputPath, saveOptions);
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
System::String fileName = u"Document.doc";
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + fileName);
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>();
saveOptions->set_CssStyleSheetType(CssStyleSheetType::External);
saveOptions->set_ExportFontResources(true);
saveOptions->set_ResourceFolder(outputDataDir + u"\\ExportResourcesUsingHtmlSaveOptions.Resources");
saveOptions->set_ResourceFolderAlias(u"http://example.com/resources");
System::String outputPath = outputDataDir + u"ExportResourcesUsingHtmlSaveOptions.html";
doc->Save(outputPath, saveOptions);
// Create Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Read the image from file, ensure it is disposed.
System::SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromFile(inputFileName);
// Clearing resources under 'using' statement
System::Details::DisposeGuard<1> imageDisposeGuard({image});
try
{
// Find which dimension the frames in this image represent. For example
// The frames of a BMP or TIFF are "page dimension" whereas frames of a GIF image are "time dimension".
System::SharedPtr<System::Drawing::Imaging::FrameDimension> dimension = System::MakeObject<System::Drawing::Imaging::FrameDimension>(image->get_FrameDimensionsList()[0]);
// Get the number of frames in the image.
int32_t framesCount = image->GetFrameCount(dimension);
// Loop through all frames.
for (int32_t frameIdx = 0; frameIdx < framesCount; frameIdx++)
{
// Insert a section break before each new page, in case of a multi-frame TIFF.
if (frameIdx != 0)
{
builder->InsertBreak(BreakType::SectionBreakNewPage);
}
// Select active frame.
image->SelectActiveFrame(dimension, frameIdx);
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
System::SharedPtr<PageSetup> ps = builder->get_PageSetup();
ps->set_PageWidth(ConvertUtil::PixelToPoint(image->get_Width(), image->get_HorizontalResolution()));
ps->set_PageHeight(ConvertUtil::PixelToPoint(image->get_Height(), image->get_VerticalResolution()));
// Insert the image into the document and position it at the top left corner of the page.
builder->InsertImage(image, RelativeHorizontalPosition::Page, 0, RelativeVerticalPosition::Page, 0, ps->get_PageWidth(), ps->get_PageHeight(), WrapType::None);
}
}
catch (...)
{
imageDisposeGuard.SetCurrentException(std::current_exception());
}
// Save the document to PDF.
doc->Save(outputFileName);
System::SharedPtr<LoadOptions> options = System::MakeObject<LoadOptions>();
options->set_AnnotationsAtBlockLevel(true);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + 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>(inputDataDir + u"OfficeMath.docx", lo);
System::String outputPath = outputDataDir + u"Load_Options.ConvertShapeToOfficeMath.docx";
//Save the document into DOCX
doc->Save(outputPath, SaveFormat::Docx);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"encrypted.odt", System::MakeObject<LoadOptions>(u"password"));
System::String outputPath = outputDataDir + u"Load_Options.LoadAndSaveEncryptedODT.odt";
doc->Save(outputPath, System::MakeObject<OdtSaveOptions>(u"newpassword"));
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>(inputDataDir + u"input.docx", lo);
System::String outputPath = outputDataDir + u"Load_Options.LoadOptionsUpdateDirtyFields.docx";
//Save the document into DOCX
doc->Save(outputPath, SaveFormat::Docx);
System::SharedPtr<FileFormatInfo> info = FileFormatUtil::DetectFileFormat(inputDataDir + u"encrypted.odt");
std::cout << info->get_IsEncrypted() << std::endl;
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
System::SharedPtr<HtmlLoadOptions> lo = System::MakeObject<HtmlLoadOptions>();
lo->set_PreferredControlType(HtmlControlType::StructuredDocumentTag);
//Load the HTML document
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"input.html", lo);
//Save the HTML document into DOCX
doc->Save(outputDataDir + u"LoadAndSaveHtmlFormFieldAsContentControlInDOCX.docx", SaveFormat::Docx);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
// Load the document from the absolute path on disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::String outputPath = outputDataDir + u"LoadAndSaveToDisk.doc";
// Save the document as DOC document.");
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
// Load the document from the absolute path on disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_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(inputDataDir + 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 = outputDataDir + u"LoadAndSaveToStream.doc";
System::IO::File::WriteAllBytes(outputPath, dstStream->ToArray());
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_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(inputDataDir + 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();
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
// The encoding of the text file is automatically detected.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"LoadTxt.txt");
// Save as any Aspose.Words supported format, such as DOCX.
System::String outputPath = outputDataDir + u"LoadTxt.docx";
doc->Save(outputPath);
// The path to the documents directory.
System::String dataDir = GetDataDir_LoadingAndSaving();
// Loads encrypted document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"LoadEncrypted.docx", System::MakeObject<LoadOptions>(u"aspose"));
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 = outputDataDir + u"SaveDocWithHtmlSaveOptions.ImportExportSVGinHTML.html";
doc->Save(outputPath, options);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.docx");
System::SharedPtr<HtmlSaveOptions> options = System::MakeObject<HtmlSaveOptions>();
options->set_MetafileFormat(HtmlMetafileFormat::EmfOrWmf);
System::String outputPath = outputDataDir + u"SaveDocWithHtmlSaveOptions.SaveHtmlWithMetafileFormat.html";
doc->Save(outputPath, options);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.docx");
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>();
saveOptions->set_CssStyleSheetType(CssStyleSheetType::External);
saveOptions->set_CssClassNamePrefix(u"pfx_");
System::String outputPath = outputDataDir + u"SaveDocWithHtmlSaveOptions.SetCssClassNamePrefix.html";
doc->Save(outputPath, saveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + u"SaveDocWithHtmlSaveOptions.SetExportCidUrlsForMhtmlResources.mhtml";
doc->Save(outputPath, saveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + u"SaveDocWithHtmlSaveOptions.SetResolveFontNames.html";
doc->Save(outputPath, saveOptions);
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Test File (doc).doc");
System::SharedPtr<HtmlFixedSaveOptions> options = System::MakeObject<HtmlFixedSaveOptions>();
options->set_UseTargetMachineFonts(true);
System::String outputPath = outputDataDir + 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>(inputDataDir + 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 = outputDataDir + u"SaveOptionsHtmlFixed.WriteAllCSSrulesinSingleFile.html";
// Save the document to disk.
doc->Save(outputPath, options);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile RenderShape.docx");
// This is the directory we want the exported images to be saved to.
System::String imagesDir = System::IO::Path::Combine(outputDataDir, 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 = outputDataDir + u"SpecifySaveOption.html";
doc->Save(outputPath, options);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::SharedPtr<DocSaveOptions> saveOptions = System::MakeObject<DocSaveOptions>();
saveOptions->set_AlwaysCompressMetafiles(false);
System::String outputPath = outputDataDir + u"WorkingWithDoc.AlwaysCompressMetafiles.doc";
doc->Save(outputPath, saveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::SharedPtr<DocSaveOptions> docSaveOptions = System::MakeObject<DocSaveOptions>();
docSaveOptions->set_Password(u"password");
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithDoc.EncryptDocumentWithPassword.doc");
doc->Save(outputPath, docSaveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(dataDir + u"Document.doc");
System::SharedPtr<OoxmlSaveOptions> ooxmlSaveOptions = System::MakeObject<OoxmlSaveOptions>();
ooxmlSaveOptions->set_Password(u"password");
System::String outputPath = dataDir + GetOutputFilePath(u"WorkingWithOoxml.EncryptDocxWithPassword.docx");
doc->Save(outputPath, ooxmlSaveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::SharedPtr<OoxmlSaveOptions> so = System::MakeObject<OoxmlSaveOptions>(SaveFormat::FlatOpc);
so->set_KeepLegacyControlChars(true);
System::String outputPath = outputDataDir + u"WorkingWithOoxml.KeepLegacyControlChars.docx";
// Save the document to disk.
doc->Save(outputPath, so);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + u"WorkingWithOoxml.SetOOXMLCompliance.docx";
doc->Save(outputPath, ooxmlSaveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::SharedPtr<OoxmlSaveOptions> ooxmlSaveOptions = System::MakeObject<OoxmlSaveOptions>();
ooxmlSaveOptions->set_UpdateLastSavedTimeProperty(true);
System::String outputPath = outputDataDir + u"WorkingWithOoxml.UpdateLastSavedTimeProperty.docx";
// Save the document to disk.
doc->Save(outputPath, ooxmlSaveOptions);
System::SharedPtr<RtfLoadOptions> loadOptions = System::MakeObject<RtfLoadOptions>();
loadOptions->set_RecognizeUtf8Text(true);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Utf8Text.rtf", loadOptions);
System::String outputPath = outputDataDir + u"WorkingWithRTF.rtf";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Input.docx");
System::SharedPtr<TxtSaveOptions> saveOptions = System::MakeObject<TxtSaveOptions>();
saveOptions->set_AddBidiMarks(true);
System::String outputPath = outputDataDir + u"WorkingWithTxt.AddBidiMarks.txt";
doc->Save(outputPath, saveOptions);
// TODO (std_string) : think about document named input_document
System::SharedPtr<Document> doc1 = System::MakeObject<Document>(inputDataDir + u"Input.docx");
doc1->Save(outputDataDir + u"WorkingWithTxt.DefaultLevelForListIndentation1.txt");
//Document doc2 = new Document("input_document");
System::SharedPtr<Document> doc2 = System::MakeObject<Document>(inputDataDir + u"Input.docx");
System::SharedPtr<TxtSaveOptions> options = System::MakeObject<TxtSaveOptions>();
doc2->Save(outputDataDir + u"WorkingWithTxt.DefaultLevelForListIndentation2.txt", options);
System::SharedPtr<TxtLoadOptions> loadOptions = System::MakeObject<TxtLoadOptions>();
loadOptions->set_DetectNumberingWithWhitespaces(false);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"LoadTxt.txt", loadOptions);
System::String outputPath = outputDataDir + u"WorkingWithTxt.DetectNumberingWithWhitespaces.docx";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TxtExportHeadersFootersMode.docx");
System::SharedPtr<TxtSaveOptions> options = System::MakeObject<TxtSaveOptions>();
options->set_SaveFormat(SaveFormat::Text);
// All headers and footers are placed at the very end of the output document.
options->set_ExportHeadersFootersMode(TxtExportHeadersFootersMode::AllAtEnd);
doc->Save(outputDataDir + u"WorkingWithTxt.ExportHeadersFootersMode.AllAtEnd.txt", options);
// Only primary headers and footers are exported at the beginning and end of each section.
options->set_ExportHeadersFootersMode(TxtExportHeadersFootersMode::PrimaryOnly);
doc->Save(outputDataDir + u"WorkingWithTxt.ExportHeadersFootersMode.PrimaryOnly.txt", options);
// No headers and footers are exported.
options->set_ExportHeadersFootersMode(TxtExportHeadersFootersMode::None);
doc->Save(outputDataDir + u"WorkingWithTxt.ExportHeadersFootersMode.None.txt", options);
System::SharedPtr<TxtLoadOptions> loadOptions = System::MakeObject<TxtLoadOptions>();
loadOptions->set_LeadingSpacesOptions(TxtLeadingSpacesOptions::Trim);
loadOptions->set_TrailingSpacesOptions(TxtTrailingSpacesOptions::Trim);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"LoadTxt.txt", loadOptions);
System::String outputPath = outputDataDir + u"WorkingWithTxt.HandleSpacesOptions.docx";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::String outputPath = outputDataDir + u"WorkingWithTxt.SaveAsTxt.txt";
doc->Save(outputPath);
// TODO (std_string) : think about document named input_document
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Input.docx");
System::SharedPtr<TxtSaveOptions> options = System::MakeObject<TxtSaveOptions>();
options->get_ListIndentation()->set_Count(3);
options->get_ListIndentation()->set_Character(u' ');
doc->Save(outputDataDir + u"WorkingWithTxt.UseSpaceCharacterPerLevelForListIndentation.txt", options);
// TODO (std_string) : think about document named input_document
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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(outputDataDir + u"WorkingWithTxt.UseTabCharacterPerLevelForListIndentation.txt", options);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"VbaProject.docm");
System::SharedPtr<VbaProject> project = doc->get_VbaProject();
System::SharedPtr<Document> destDoc = System::MakeObject<Document>();
destDoc->set_VbaProject(System::MakeObject<VbaProject>());
// Clone a single module.
System::SharedPtr<VbaModule> copyModule = doc->get_VbaProject()->get_Modules()->idx_get(0)->Clone();
destDoc->get_VbaProject()->get_Modules()->Add(copyModule);
destDoc->Save(inputDataDir + u"output.docm");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"VbaProject.docm");
System::SharedPtr<VbaProject> project = doc->get_VbaProject();
System::SharedPtr<Document> destDoc = System::MakeObject<Document>();
// Clone the whole project.
destDoc->set_VbaProject(doc->get_VbaProject()->Clone());
destDoc->Save(inputDataDir + u"output.docm");
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Create a new VBA project.
System::SharedPtr<VbaProject> project = System::MakeObject<VbaProject>();
project->set_Name(u"AsposeProject");
doc->set_VbaProject(project);
// Create a new module and specify a macro source code.
System::SharedPtr<VbaModule> vbModule = System::MakeObject<VbaModule>();
vbModule->set_Name(u"AsposeModule");
vbModule->set_Type(VbaModuleType::ProceduralModule);
vbModule->set_SourceCode(u"New source code");
// Add module to the VBA project.
doc->get_VbaProject()->get_Modules()->Add(vbModule);
doc->Save(outputDataDir + u"VbaProject_out.docm");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"test.docm");
System::SharedPtr<VbaProject> project = doc->get_VbaProject();
System::String newSourceCode = u"Test change source code";
// Choose a module, and set a new source code.
project->get_Modules()->idx_get(0)->set_SourceCode(newSourceCode);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.dot");
if (doc->get_VbaProject() != nullptr)
{
for (System::SharedPtr<VbaModule> module : System::IterateOver(doc->get_VbaProject()->get_Modules()))
{
std::cout << module->get_SourceCode().ToUtf8String() << std::endl;
}
}
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_MailMergeAndReporting();
System::String outputDataDir = GetOutputDataDir_MailMergeAndReporting();
// Open an existing document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + 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);
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->InsertHtml(System::ObjectExt::ToString(e->get_FieldValue()));
e->set_Text(u"");
}
}
}
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_MailMergeAndReporting();
System::String outputDataDir = GetOutputDataDir_MailMergeAndReporting();
// Open an existing document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + u"MailMergeAndConditionalField.docx";
doc->Save(outputPath);
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"MailMerge.CleanupPunctuationMarks.docx");
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 = outputDataDir + u"MailMergeCleanUp.CleanupParagraphsWithPunctuationMarks.docx";
// Save the output document to disk.
doc->Save(outputPath);
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->InsertHtml(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;
}
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_MailMergeAndReporting();
System::String outputDataDir = GetOutputDataDir_MailMergeAndReporting();
//System::String fileName = u"Template.doc";
// Load the template document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + u"MailMergeFormFields.doc";
// Save the finished document.
doc->Save(outputPath);
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;
}
}
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_MailMergeAndReporting();
System::String outputDataDir = GetOutputDataDir_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>(inputDataDir + 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 = outputDataDir + u"NestedMailMergeCustom.doc";
doc->Save(outputPath);
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_MailMergeAndReporting();
System::String outputDataDir = GetOutputDataDir_MailMergeAndReporting();
// Open an existing document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + 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);
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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");
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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.");
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"BookmarkTable.doc";
doc->Save(outputPath);
// // Create empty document
// System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Bookmark.Table_out.doc");
//
// for (System::SharedPtr<Bookmark> bookmark : System::IterateOver<Bookmark>(doc->get_Range()->get_Bookmarks()))
// {
// //std::cout << "Bookmark: " << bookmark->get_Name << (bookmark->get_IsColumn() ? " (Column)" : "") << std::endl;
// if (bookmark->get_IsColumn())
// {
// System::SharedPtr<Row> row = System::MakeObject<Row>(bookmark->get_BookmarkStart()->GetAncestor(NodeType::Row));
// if (row != NULL && bookmark->get_FirstColumn() < row->get_Cells()->get_Count())
// {
// //std::cout << row->get_Cells()->idx_get(bookmark->get_FirstColumn())->GetText()->TrimEnd(ControlChar::CellChar) << std::endl;
// }
// }
// }
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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<PdfSaveOptions> options = System::MakeObject<PdfSaveOptions>();
options->get_OutlineOptions()->get_BookmarksOutlineLevels()->Add(u"My Bookmark", 1);
options->get_OutlineOptions()->get_BookmarksOutlineLevels()->Add(u"Nested Bookmark", 2);
System::String outputPath = outputDataDir + u"CreateBookmark.pdf";
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 = outputDataDir + u"ChartNumberFormat.docx";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + 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 = outputDataDir + 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 = outputDataDir + u"CreateColumnChart.InsertSimpleColumnChart.doc";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"InsertAreaChart.docx";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"InsertBubbleChart.docx";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + 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 = outputDataDir + 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 = outputDataDir + 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 = outputDataDir + 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 = outputDataDir + 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 = outputDataDir + 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 = outputDataDir + u"WorkingWithChartAxis.SetNumberFormatForAxis.docx";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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(outputDataDir + u"WorkingWithChartAxis.TickMultiLineLabelAlignment.docx");
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"WorkWithChartDataLabel.docx";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Shape> shape = builder->InsertChart(ChartType::Pie, 432, 252);
System::SharedPtr<Chart> chart = shape->get_Chart();
chart->get_Series()->Clear();
System::SharedPtr<ChartSeries> series = chart->get_Series()->Add(u"Series 1", System::MakeArray<System::String>({u"Category1", u"Category2", u"Category3"}), System::MakeArray<double>({2.7, 3.2, 0.8}));
System::SharedPtr<ChartDataLabelCollection> labels = series->get_DataLabels();
labels->set_ShowPercentage(true);
labels->set_ShowValue(true);
labels->set_ShowLeaderLines(false);
labels->set_Separator(u" - ");
System::String outputPath = outputDataDir + u"WorkWithChartDataLabels.DefaultOptionsForDataLabels.docx";
doc->Save(outputPath);
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 = outputDataDir + u"WorkWithChartDataLabels.WorkWithChartDataLabel.docx";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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(MarkerSymbol::Star);
dataPoint12->get_Marker()->set_Size(20);
System::String outputPath = outputDataDir + 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);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"AddComments.doc";
// Save the document.
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Write(u"Some text is added.");
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"AnchorComment.doc";
// Save the document.
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithComments();
System::String outputDataDir = GetOutputDataDir_WorkingWithComments();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + u"CommentReply.doc";
// Save the document to disk.
doc->Save(outputPath);
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);
}
}
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;
}
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;
}
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithComments();
System::String outputDataDir = GetOutputDataDir_WorkingWithComments();
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Extract the information about the comments of all the authors.
for (System::String const &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 (System::String const &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 = outputDataDir + u"ProcessComments.doc";
// Save the document.
doc->Save(outputPath);
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();
}
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 directories.
System::String inputDataDir = GetInputDataDir_WorkingWithComments();
System::String outputDataDir = GetOutputDataDir_WorkingWithComments();
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + u"RemoveRegionText.doc";
// Save the document.
doc->Save(outputPath);
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));
System::String text = u"test\r";
// Replace "\r" control character with "\r\n"
text = text.Replace(ControlChar::Cr(), ControlChar::CrLf());
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
// Load the template document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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();
}
}
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"AddGroupShapeToDocument.doc";
// Save the document to disk.
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"CheckBoxTypeContentControl.docx";
doc->Save(outputPath, SaveFormat::Docx);
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::SharedPtr<RunCollection> runs = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs();
System::SharedPtr<Font> runFont = runs->idx_get(0)->get_Font();
// One run might have several Dml text effects applied.
std::cout << runFont->HasDmlEffect(TextDmlEffect::Shadow) << std::endl;
std::cout << runFont->HasDmlEffect(TextDmlEffect::Effect3D) << std::endl;
std::cout << runFont->HasDmlEffect(TextDmlEffect::Reflection) << std::endl;
std::cout << runFont->HasDmlEffect(TextDmlEffect::Outline) << std::endl;
std::cout << runFont->HasDmlEffect(TextDmlEffect::Fill) << std::endl;
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + 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 = outputDataDir + u"CleansUnusedStylesandLists.docx";
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<Document> clone = doc->Clone();
System::String outputPath = outputDataDir + u"CloningDocument.doc";
// Save the document to disk.
clone->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_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 = outputDataDir + u"ComboBoxContentControl.docx";
doc->Save(outputPath);
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;
// 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 (endNode->get_NodeType() == NodeType::CommentRangeEnd && isInclusive)
{
System::SharedPtr<Node> node = FindNextNode(NodeType::Comment, endNode->get_NextSibling());
if (node != nullptr)
{
endNode = node;
}
}
// 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
startNode = GetAncestorInBody(startNode);
endNode = GetAncestorInBody(endNode);
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)
{
// We need to process each marker separately so pass it off to a separate method instead.
// End should be processed at first to keep node indexes.
if (isEndingNode)
{
// !isStartingNode: don't add the node twice if the markers are the same node.
ProcessMarker(cloneNode, nodes, originalEndNode, currNode, isInclusive, false, !isStartingNode, false);
isExtracting = false;
}
// Conditional needs to be separate as the block level start and end markers maybe the same node.
if (isStartingNode)
{
ProcessMarker(cloneNode, nodes, originalStartNode, currNode, isInclusive, true, true, false);
isStartingNode = 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();
}
}
// For compatibility with mode with inline bookmarks, add the next paragraph (empty).
if (isInclusive && originalEndNode == endNode && !originalEndNode->get_IsComposite())
{
IncludeNextParagraph(endNode, nodes);
}
// Return the nodes between the node markers.
return nodes;
}
System::SharedPtr<Node> GetAncestorInBody(System::SharedPtr<Node> startNode)
{
while (startNode->get_ParentNode()->get_NodeType() != NodeType::Body)
{
startNode = startNode->get_ParentNode();
}
return startNode;
}
std::vector<System::SharedPtr<Node>> FillSelfAndParents(System::SharedPtr<Node> node, System::SharedPtr<Node> tillNode)
{
std::vector<System::SharedPtr<Node>> dest;
System::SharedPtr<Node> currentNode = node;
while (currentNode != tillNode)
{
dest.push_back(currentNode);
currentNode = currentNode->get_ParentNode();
}
return dest;
}
void RemoveNodesOutsideOfRange(System::SharedPtr<Node> markerNode, bool isInclusive, bool isStartMarker)
{
// Remove the nodes up to/from the marker.
bool isSkip = false;
bool isProcessing = true;
bool isRemoving = isStartMarker;
System::SharedPtr<Node> nextNode = markerNode->get_ParentNode()->get_FirstChild();
while (isProcessing && nextNode != nullptr)
{
System::SharedPtr<Node> currentNode = nextNode;
isSkip = false;
if (System::ObjectExt::Equals(currentNode, markerNode))
{
if (isStartMarker)
{
isProcessing = false;
if (isInclusive)
{
isRemoving = false;
}
}
else
{
isRemoving = true;
if (isInclusive)
{
isSkip = true;
}
}
}
nextNode = nextNode->get_NextSibling();
if (isRemoving && !isSkip)
{
currentNode->Remove();
}
}
}
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(