Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active September 22, 2020 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/518f03cac02abb105e02f55edb7de9f9 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/518f03cac02abb105e02f55edb7de9f9 to your computer and use it in GitHub Desktop.
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 inputDataDir = GetInputDataDir_LoadingAndSaving();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Test File (doc).doc");
for (auto signature : System::IterateOver(doc->get_DigitalSignatures()))
{
std::cout << "*** Signature Found ***" << std::endl;
std::cout << "Is valid: " << signature->get_IsValid() << std::endl;
std::cout << "Reason for signing: " << signature->get_Comments().ToUtf8String() << std::endl;
// This property is available in MS Word documents only.
std::cout << "Time of signing: " << signature->get_SignTime().ToString().ToUtf8String() << std::endl;
std::cout << "Subject name: " << signature->get_CertificateHolder()->get_Certificate()->get_SubjectName()->get_Name().ToUtf8String() << std::endl;
std::cout << "Issuer name: " << signature->get_CertificateHolder()->get_Certificate()->get_IssuerName()->get_Name().ToUtf8String() << std::endl;
}
// The path to the documents directory.
System::String dataDir = GetInputDataDir_LoadingAndSaving();
System::String supportedDir = dataDir + u"Supported_out";
System::String unknownDir = dataDir + u"Unknown_out";
System::String encryptedDir = dataDir + u"Encrypted_out";
System::String pre97Dir = dataDir + u"Pre97_out";
// 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::Docx);
// 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);
// 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);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Load the document into Aspose.Words.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Test File (docx).docx");
// Save into a memory stream in MHTML format.
System::SharedPtr<System::IO::MemoryStream> stream = System::MakeObject<System::IO::MemoryStream>();
doc->Save(stream, SaveFormat::Mhtml);
// Rewind the stream to the beginning so Aspose.Email can read it.
stream->set_Position(0);
// Create an Aspose.Network MIME email message from the stream.
System::SharedPtr<Aspose::Email::MailMessage > message = System::MakeObject<Aspose::Email::MailMessage>();
//message->Load(stream, System::MakeObject<Aspose::Email::MhtmlLoadOptions>());
message->set_From(u"sender@sender.com");
message->get_To()->Add(u"receiver@gmail.com");
message->set_Subject(u"Aspose.Words + Aspose.Email MHTML Test Message");
// Send the message using Aspose.Email
System::SharedPtr<Aspose::Email::Clients::Smtp::SmtpClient> client = System::MakeObject<Aspose::Email::Clients::Smtp::SmtpClient>();
client->set_Host(u"mail.server.com");
client->set_Username(u"username");
client->set_Password(u"password");
client->set_Port(587);
client->Send(message);
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Test File (docx).docx");
// Save the document into HTML.
doc->Save(outputDataDir + u"Document_out.html", SaveFormat::Html);
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::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::SharedPtr<HtmlSaveOptions> saveOptions = System::MakeObject<HtmlSaveOptions>();
saveOptions->set_CssStyleSheetType(CssStyleSheetType::External);
saveOptions->set_ExportFontResources(true);
saveOptions->set_ResourceFolder(outputDataDir + u"\\Resources");
doc->Save(outputDataDir + u"ExportResourcesUsingHtmlSaveOptions.html", 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;
}
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetInputDataDir_LoadingAndSaving();
// Create a simple document from scratch.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Test Signed PDF.");
System::SharedPtr<PdfSaveOptions> options = System::MakeObject<PdfSaveOptions>();
options->set_DigitalSignatureDetails(System::MakeObject<PdfDigitalSignatureDetails>(CertificateHolder::Create(inputDataDir + u"CioSrv1.pfx", u"cinD96..arellA"), u"reason", u"location", System::DateTime::get_Now()));
System::String outputPath = outputDataDir + u"DigitallySignedPdfUsingCertificateHolder.Signed_out.pdf";
doc->Save(outputPath, options);
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Rendering.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"Rendering.doc");
System::String outputPath = outputDataDir + u"Doc2Pdf.SaveDoc2Pdf.pdf";
// Save the document in PDF format.
doc->Save(outputPath);
class HandleDocumentWarnings : public IWarningCallback {
using ThisType = HandleDocumentWarnings;
using BaseType = IWarningCallback;
using ThisTypeBaseTypesInfo = ::System::BaseTypesInfo<BaseType>;
RTTI_INFO(ThisType, ThisTypeBaseTypesInfo);
public:
System::SharedPtr<WarningInfoCollection> mWarnings;
void Warning(System::SharedPtr<WarningInfo> info) override;
HandleDocumentWarnings();
};
void HandleDocumentWarnings::Warning(System::SharedPtr<WarningInfo> info)
{
//For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
if (info->get_WarningType() == WarningType::MinorFormattingLoss)
{
std::cout << "Unsupported operation: " << info->get_Description().ToUtf8String() << std::endl;
mWarnings->Warning(info);
}
}
HandleDocumentWarnings::HandleDocumentWarnings() : mWarnings(System::MakeObject<WarningInfoCollection>())
{
}
void RenderMetafileToBitmap(System::String const& inputDataDir, System::String const& outputDataDir)
{
// Load the document from disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"PdfRenderWarnings.doc");
System::SharedPtr<MetafileRenderingOptions> metafileRenderingOptions = System::MakeObject<MetafileRenderingOptions>();
metafileRenderingOptions->set_EmulateRasterOperations(false);
metafileRenderingOptions->set_RenderingMode(MetafileRenderingMode::VectorWithFallback);
// If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
System::SharedPtr<HandleDocumentWarnings> callback = System::MakeObject<HandleDocumentWarnings>();
doc->set_WarningCallback(callback);
System::SharedPtr<PdfSaveOptions> saveOptions = System::MakeObject<PdfSaveOptions>();
saveOptions->set_MetafileRenderingOptions(metafileRenderingOptions);
doc->Save(outputDataDir + u"PdfSaveOptions.HandleRasterWarnings.pdf", saveOptions);
}
// 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);
void ConvertImageToPdf(System::String const &inputFileName, System::String const &outputFileName)
{
std::cout << "Converting " << inputFileName.ToUtf8String() << " to PDF ...." << std::endl;
// 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
{
// Insert a section break before each new page, in case of a multi-frame TIFF.
builder->InsertBreak(BreakType::SectionBreakNewPage);
// 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);
}
ConvertImageToPdf(inputDataDir + u"Test.jpg", outputDataDir + u"ImageToPdf_Jpg.pdf");
ConvertImageToPdf(inputDataDir + u"Test.png", outputDataDir + u"ImageToPdf_Png.pdf");
ConvertImageToPdf(inputDataDir + u"Test.wmf", outputDataDir + u"ImageToPdf_Wmf.pdf");
ConvertImageToPdf(inputDataDir + u"Test.tiff", outputDataDir + u"ImageToPdf_Tiff.pdf");
ConvertImageToPdf(inputDataDir + u"Test.gif", outputDataDir + u"ImageToPdf_Gif.pdf");
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);
class DocumentLoadingWarningCallback : public IWarningCallback
{
public:
System::SharedPtr<WarningInfoCollection> mWarnings;
void Warning(System::SharedPtr<WarningInfo> info) override;
DocumentLoadingWarningCallback();
};
void DocumentLoadingWarningCallback::Warning(System::SharedPtr<WarningInfo> info)
{
// Prints warnings and their details as they arise during document loading.
std::cout << "WARNING: {info->get_WarningType} " << std::endl;
std::cout << "Source: {info->get_Source} " << std::endl;
std::cout << "\tDescription: {info->get_Description} " << std::endl;
}
DocumentLoadingWarningCallback::DocumentLoadingWarningCallback() : mWarnings(System::MakeObject<WarningInfoCollection>())
{
}
class HtmlLinkedResourceLoadingCallback : public IResourceLoadingCallback
{
public:
ResourceLoadingAction ResourceLoading(System::SharedPtr<ResourceLoadingArgs> args) override;
HtmlLinkedResourceLoadingCallback();
};
HtmlLinkedResourceLoadingCallback::HtmlLinkedResourceLoadingCallback()
{
}
ResourceLoadingAction HtmlLinkedResourceLoadingCallback::ResourceLoading(System::SharedPtr<ResourceLoadingArgs> args)
{
switch (args->get_ResourceType())
{
case ResourceType::CssStyleSheet:
{
std::cout << "External CSS Stylesheet found upon loading: " << args->get_OriginalUri().ToUtf8String() << std::endl;
// CSS file will don't used in the document
return ResourceLoadingAction::Skip;
}
case ResourceType::Image:
{
// Replaces all images with a substitute
System::String newImageFilename = u"Logo.jpg";
std::cout << "\tImage will be substituted with: " << newImageFilename.ToUtf8String() << std::endl;
System::SharedPtr<System::Drawing::Image> newImage = System::Drawing::Image::FromFile(GetInputDataDir_LoadingAndSaving() + newImageFilename);
System::SharedPtr<System::Drawing::ImageConverter> converter = System::MakeObject<System::Drawing::ImageConverter>();
auto imageBytes = System::DynamicCast<System::Array<uint8_t>>(converter->ConvertTo(nullptr, nullptr, newImage, System::ObjectExt::GetType<System::Array<uint8_t>>()));
//System::ArrayPtr<uint8_t> imageBytes = System::IO::File::ReadAllBytes(GetInputDataDir_LoadingAndSaving() + newImageFilename);
args->SetData(imageBytes);
// New images will be used instead of presented in the document
return ResourceLoadingAction::UserProvided;
}
case ResourceType::Document:
{
std::cout << "External document found upon loading: " << args->get_OriginalUri().ToUtf8String() << std::endl;
// Will be used as usual
return ResourceLoadingAction::Default;
}
default:
throw System::InvalidOperationException(u"Unexpected ResourceType value.");
}
}
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"));
// Set the Encoding attribute in a LoadOptions object to override the automatically chosen encoding with the one we know to be correct
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
loadOptions->set_Encoding(System::Text::Encoding::get_UTF7());
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Encoded in UTF-7.txt", loadOptions);
// Create a new LoadOptions object and set its ResourceLoadingCallback attribute as an instance of our IResourceLoadingCallback implementation
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
loadOptions->set_ResourceLoadingCallback(System::MakeObject<HtmlLinkedResourceLoadingCallback>());
// When we open an Html document, external resources such as references to CSS stylesheet files and external images
// will be handled in a custom manner by the loading callback as the document is loaded
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Images.html", loadOptions);
doc->Save(inputDataDir + u"Document.LoadOptionsCallback_out.pdf");
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);
// Create a new LoadOptions object and set its WarningCallback property.
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
System::SharedPtr<DocumentLoadingWarningCallback> callback = System::MakeObject<DocumentLoadingWarningCallback>();
loadOptions->set_WarningCallback(callback);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.docx", loadOptions);
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
// Change the loading version to Microsoft Word 2010.
loadOptions->set_MswVersion(MsWordVersion::Word2010);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"document.docx", loadOptions);
System::String outputPath = outputDataDir + u"Load_Options.SetMSWordVersion.docx";
doc->Save(outputPath);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
loadOptions->set_TempFolder(u"C:/TempFolder/");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"document.docx", loadOptions);
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.docx");
System::String outputPath = outputDataDir + u"LoadAndSaveToDisk.docx";
// 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.docx");
// 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.docx");
// 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.docx";
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.docx");
// 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 = GetInputDataDir_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);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.Signed.docx");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<SignatureLine> signatureLine = builder->InsertSignatureLine(System::MakeObject<SignatureLineOptions>())->get_SignatureLine();
signatureLine->set_ProviderId(System::Guid(u"{F5AC7D23-DA04-45F5-ABCB-38CE7A982553}"));
doc->Save(outputDataDir + u"SigningSignatureLine.CreateNewSignatureLineAndSetProviderID1_out.docx");
System::SharedPtr<SignOptions> signOptions = System::MakeObject<SignOptions>();
signOptions->set_SignatureLineId(signatureLine->get_Id());
signOptions->set_ProviderId(signatureLine->get_ProviderId());
System::SharedPtr<CertificateHolder> certHolder = CertificateHolder::Create(inputDataDir + u"signature.pfx", u"signature");
System::String outputPath = outputDataDir + u"SigningSignatureLine.CreateNewSignatureLineAndSetProviderID2_out.docx";
DigitalSignatureUtil::Sign(inputDataDir + u"Document.Signed.docx", outputPath, certHolder, signOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<SignatureLine> signatureLine = builder->InsertSignatureLine(System::MakeObject<SignatureLineOptions>())->get_SignatureLine();
doc->Save(outputDataDir + u"SigningSignatureLine.CreatingAndSigningNewSignatureLine1_out.docx");
System::SharedPtr<SignOptions> signOptions = System::MakeObject<SignOptions>();
signOptions->set_SignatureLineId(signatureLine->get_Id());
signOptions->set_SignatureLineImage(System::IO::File::ReadAllBytes(inputDataDir + u"SignatureImage.emf"));
System::SharedPtr<CertificateHolder> certHolder = CertificateHolder::Create(inputDataDir + u"signature.pfx", u"signature");
System::String outputPath = outputDataDir + u"SigningSignatureLine.CreatingAndSigningNewSignatureLine2_out.docx";
DigitalSignatureUtil::Sign(inputDataDir + u"Document.NewSignatureLine.docx", outputPath, certHolder, signOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.Signed.docx");
System::SharedPtr<SignatureLine> signatureLine = (System::DynamicCast<Aspose::Words::Drawing::Shape>(doc->get_FirstSection()->get_Body()->GetChild(Aspose::Words::NodeType::Shape, 0, true)))->get_SignatureLine();
//Set signature and signature line provider ID
System::SharedPtr<SignOptions> signOptions = System::MakeObject<SignOptions>();
signOptions->set_ProviderId(signatureLine->get_ProviderId());
signOptions->set_SignatureLineId(signatureLine->get_Id());
System::SharedPtr<CertificateHolder> certHolder = CertificateHolder::Create(inputDataDir + u"signature.pfx", u"signature");
System::String outputPath = outputDataDir + u"SigningSignatureLine.SetSignatureProviderID_out.docx";
DigitalSignatureUtil::Sign(inputDataDir + u"Document.Signed.docx", outputPath, certHolder, signOptions);
System::SharedPtr<SignOptions> signOptions = System::MakeObject<SignOptions>();
signOptions->set_DecryptionPassword(u"decryptionPassword");
System::SharedPtr<CertificateHolder> certHolder = CertificateHolder::Create(inputDataDir + u"signature.pfx", u"signature");
System::String outputPath = outputDataDir + u"SigningSignatureLine.SigningEncryptedDocument_out.docx";
DigitalSignatureUtil::Sign(inputDataDir + u"Document.Signed.docx", outputPath, certHolder, signOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.Signed.docx");
System::SharedPtr<SignatureLine> signatureLine = (System::DynamicCast<Aspose::Words::Drawing::Shape>(doc->get_FirstSection()->get_Body()->GetChild(Aspose::Words::NodeType::Shape, 0, true)))->get_SignatureLine();
System::SharedPtr<SignOptions> signOptions = System::MakeObject<SignOptions>();
signOptions->set_SignatureLineId(signatureLine->get_Id());
signOptions->set_SignatureLineImage(System::IO::File::ReadAllBytes(inputDataDir + u"SignatureImage.emf"));
System::SharedPtr<CertificateHolder> certHolder = CertificateHolder::Create(inputDataDir + u"signature.pfx", u"signature");
System::String outputPath = outputDataDir + u"SigningSignatureLine.SigningExistingSignatureLine_out.docx";
DigitalSignatureUtil::Sign(inputDataDir + u"Document.Signed.docx", outputPath, certHolder, signOptions);
System::SharedPtr<CertificateHolder> certHolder = CertificateHolder::Create(inputDataDir + u"signature.pfx", u"signature");
System::String outputPath = outputDataDir + u"SigningSignatureLine.SimpleDocumentSigning_out.docx";
DigitalSignatureUtil::Sign(inputDataDir + u"Document.Signed.docx", outputPath, certHolder);
auto builder = System::MakeObject<DocumentBuilder>();
// Create a new table with two cells.
builder->InsertCell();
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Right);
builder->Write(u"Cell1");
builder->InsertCell();
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->Write(u"Cell2");
auto saveOptions = System::MakeObject<MarkdownSaveOptions>();
// Makes all paragraphs inside table to be aligned to Left.
saveOptions->set_TableContentAlignment(TableContentAlignment::Left);
builder->get_Document()->Save(outputDataDir + u"left.md", saveOptions);
// Makes all paragraphs inside table to be aligned to Right.
saveOptions->set_TableContentAlignment(TableContentAlignment::Right);
builder->get_Document()->Save(outputDataDir + u"right.md", saveOptions);
// Makes all paragraphs inside table to be aligned to Center.
saveOptions->set_TableContentAlignment(TableContentAlignment::Center);
builder->get_Document()->Save(outputDataDir + u"center.md", saveOptions);
// Makes all paragraphs inside table to be aligned automatically.
// The alignment in this case will be taken from the first paragraph in corresponding table column.
saveOptions->set_TableContentAlignment(TableContentAlignment::Auto);
builder->get_Document()->Save(outputDataDir + u"auto.md", saveOptions);
auto builder = System::MakeObject<DocumentBuilder>();
builder->Writeln(u"Some text!");
// specify MarkDownSaveOptions
auto saveOptions = SaveOptions::CreateSaveOptions(SaveFormat::Markdown);
builder->get_Document()->Save(outputDataDir + u"TestDocument.md", saveOptions);
// 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>(inputDataDir + u"Document.doc");
System::SharedPtr<DocSaveOptions> docSaveOptions = System::MakeObject<DocSaveOptions>();
docSaveOptions->set_Password(u"password");
System::String outputPath = outputDataDir + u"WorkingWithDoc.EncryptDocumentWithPassword.doc";
doc->Save(outputPath, docSaveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"in.doc");
System::SharedPtr<DocSaveOptions> saveOptions = System::DynamicCast<DocSaveOptions>(SaveOptions::CreateSaveOptions(SaveFormat::Doc));
saveOptions->set_SavePictureBullet(false);
auto outputPath = outputDataDir + u"out.doc";
doc->Save(outputPath, saveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::SharedPtr<OoxmlSaveOptions> ooxmlSaveOptions = System::MakeObject<OoxmlSaveOptions>();
ooxmlSaveOptions->set_Password(u"password");
System::String outputPath = outputDataDir + 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");
System::SharedPtr<OoxmlSaveOptions> so = System::MakeObject<OoxmlSaveOptions>(SaveFormat::Docx);
so->set_CompressionLevel(CompressionLevel::SuperFast);
// Save the document to disk.
System::String outputPath = outputDataDir + u"WorkingWithOoxml.SetCompressionLevel.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);
System::SharedPtr<Document> doc1 = System::MakeObject<Document>(inputDataDir + u"input_document");
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);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"input_document");
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);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"input_document");
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(u"AsposeModule")->Clone();
destDoc->get_VbaProject()->get_Modules()->Add(copyModule);
destDoc->Save(outputDataDir + u"WorkingWithVbaMacros.CloneVbaModule.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(outputDataDir + u"WorkingWithVbaMacros.CloneVbaProject.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"WorkingWithVbaMacros.CreateVbaMacros.docm");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"VbaProject.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"VbaProject.docm");
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;
}
}
/// <summary>
/// Returns path from a specified identifier of an Automation type library.
/// </summary>
/// <remarks>
/// Please see details for the syntax at [MS-OVBA], 2.1.1.8 LibidReference.
/// </remarks>
System::String GetLibIdReferencePath(const System::String& libIdReference)
{
if (!System::String::IsNullOrEmpty(libIdReference))
{
auto refPaths = libIdReference.Split(u'#');
if (refPaths->get_Length() > 3)
{
return refPaths[3];
}
}
return u"";
}
/// <summary>
/// Returns path from a specified identifier of an Automation type library.
/// </summary>
/// <remarks>
/// Please see details for the syntax at [MS-OVBA], 2.1.1.12 ProjectReference.
/// </remarks>
System::String GetLibIdProjectPath(const System::String& libIdProject)
{
return !System::String::IsNullOrEmpty(libIdProject) ? libIdProject.Substring(3) : u"";
}
/// <summary>
/// Returns string representing LibId path of a specified reference.
/// </summary>
System::String GetLibIdPath(const System::SharedPtr<Aspose::Words::VbaReference>& reference)
{
switch (reference->get_Type())
{
case Aspose::Words::VbaReferenceType::Registered:
case Aspose::Words::VbaReferenceType::Original:
case Aspose::Words::VbaReferenceType::Control:
return GetLibIdReferencePath(reference->get_LibId());
case Aspose::Words::VbaReferenceType::Project:
return GetLibIdProjectPath(reference->get_LibId());
default: ;
throw System::ArgumentOutOfRangeException();
}
}
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(ThisType, ThisTypeBaseTypesInfo);
public:
void FieldMerging(System::SharedPtr<FieldMergingArgs> e) override;
void ImageFieldMerging(System::SharedPtr<ImageFieldMergingArgs> args) override {}
};
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(ThisType, ThisTypeBaseTypesInfo);
public:
void FieldMerging(System::SharedPtr<FieldMergingArgs> e) override;
void ImageFieldMerging(System::SharedPtr<ImageFieldMergingArgs> args) override {}
private:
System::SharedPtr<DocumentBuilder> mBuilder;
};
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);
}
}
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);
class DataSourceRoot : public IMailMergeDataSourceRoot
{
public:
System::SharedPtr<IMailMergeDataSource> IMailMergeDataSourceRoot::GetDataSource(System::String s) override
{
return System::MakeObject<DataSource>();
}
private:
class DataSource : public IMailMergeDataSource
{
private:
bool next { true };
public:
System::String get_TableName() override {
return u"example";
}
bool MoveNext() override {
bool result = next;
next = false;
return result;
}
bool GetValue(System::String fieldName, System::SharedPtr<System::Object>& fieldValue) override {
return false;
}
System::SharedPtr<IMailMergeDataSource> GetChildDataSource(System::String tableName) override {
return nullptr;
}
};
};
class ImageFieldMergingHandler : public IFieldMergingCallback
{
typedef ImageFieldMergingHandler ThisType;
typedef IFieldMergingCallback BaseType;
typedef System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO(ThisType, ThisTypeBaseTypesInfo);
public:
void FieldMerging(System::SharedPtr<FieldMergingArgs> e) override {}
void ImageFieldMerging(System::SharedPtr<ImageFieldMergingArgs> args) override;
};
void ImageFieldMergingHandler::ImageFieldMerging(System::SharedPtr<ImageFieldMergingArgs> e)
{
System::SharedPtr<Shape> shape = System::MakeObject<Shape>(e->get_Document(), ShapeType::Image);
shape->set_Width(126);
shape->set_Height(126);
shape->set_WrapType(WrapType::Square);
System::String imageFileName = GetInputDataDir_MailMergeAndReporting() + u"image.png";
shape->get_ImageData()->SetImage(imageFileName);
e->set_Shape(shape);
}
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.docx");
doc->get_MailMerge()->set_UseNonMergeFields(true);
doc->get_MailMerge()->set_TrimWhitespaces(true);
doc->get_MailMerge()->set_UseWholeParagraphAsRegion(false);
doc->get_MailMerge()->set_CleanupOptions(MailMergeCleanupOptions::RemoveEmptyTableRows
| MailMergeCleanupOptions::RemoveContainingFields
| MailMergeCleanupOptions::RemoveUnusedRegions
| MailMergeCleanupOptions::RemoveUnusedFields);
// Add a handler for the MergeField event.
doc->get_MailMerge()->set_FieldMergingCallback(System::MakeObject<ImageFieldMergingHandler>());
doc->get_MailMerge()->ExecuteWithRegions(System::MakeObject<DataSourceRoot>());
System::String outputPath = outputDataDir + u"ImageMailMerge_out.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.");
// 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"BookmarkTable.doc");
for (System::SharedPtr<Bookmark> bookmark : System::IterateOver<Bookmark>(doc->get_Range()->get_Bookmarks()))
{
std::cout << "Bookmark: " << bookmark->get_Name().ToUtf8String() << (bookmark->get_IsColumn() ? " (Column)" : "") << std::endl;
if (bookmark->get_IsColumn())
{
System::SharedPtr<Row> row = System::StaticCast<Row>(bookmark->get_BookmarkStart()->GetAncestor(NodeType::Row));
if (row != nullptr && bookmark->get_FirstColumn() < row->get_Cells()->get_Count())
{
std::cout << row->get_Cells()->idx_get(bookmark->get_FirstColumn())->GetText().TrimEnd(ControlChar::CellChar).ToUtf8String() << 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);
typedef System::SharedPtr<System::Object> TObjectPtr;
System::String bookmarkName = u"Bookmark2";
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithBookmarks();
System::String outputDataDir = GetOutputDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Bookmarks.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Bookmark> bm = doc->get_Range()->get_Bookmarks()->idx_get(bookmarkName);
builder->MoveToDocumentEnd();
// {IF "{MERGEFIELD bookmark}" = "true" "" ""}
System::SharedPtr<Field> field = builder->InsertField(u"IF \"", nullptr);
builder->MoveTo(field->get_FieldStart()->get_NextSibling());
builder->InsertField(System::String(u"MERGEFIELD ") + bookmarkName + u"", nullptr);
builder->Write(u"\" = \"true\" ");
builder->Write(u"\"");
builder->Write(u"\"");
builder->Write(u" \"\"");
System::SharedPtr<Node> currentNode = field->get_FieldStart();
bool flag = true;
while (currentNode != nullptr && flag)
{
if (currentNode->get_NodeType() == Aspose::Words::NodeType::Run)
{
if (System::ObjectExt::Equals(currentNode->ToString(Aspose::Words::SaveFormat::Text).Trim(), u"\""))
{
flag = false;
}
}
System::SharedPtr<Node> nextNode = currentNode->get_NextSibling();
bm->get_BookmarkStart()->get_ParentNode()->InsertBefore(currentNode, bm->get_BookmarkStart());
currentNode = nextNode;
}
System::SharedPtr<Node> endNode = bm->get_BookmarkEnd();
flag = true;
while (currentNode != nullptr && flag)
{
if (currentNode->get_NodeType() == Aspose::Words::NodeType::FieldEnd)
{
flag = false;
}
System::SharedPtr<Node> nextNode = currentNode->get_NextSibling();
bm->get_BookmarkEnd()->get_ParentNode()->InsertAfter(currentNode, endNode);
endNode = currentNode;
currentNode = nextNode;
}
doc->get_MailMerge()->Execute(System::MakeArray<System::String>({bookmarkName}), System::MakeArray<TObjectPtr>({System::ObjectExt::Box<bool>(false)}));
//MailMerge can be avoided by using the following
//builder.MoveToMergeField(bookmarkName);
//builder.Write(showHide ? "true" : "false");
doc->Save(outputDataDir + u"Updated_Document_out.doc");
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> series1 = chart->get_Series()->Add(u"AW Series 1", System::MakeArray<System::String>({u"AW0", u"AW1", u"AW2"}), System::MakeArray<double>({2.5, 1.5, 3.5}));
series1->set_HasDataLabels(true);
series1->get_DataLabels()->set_ShowValue(true);
series1->get_DataLabels()->idx_get(0)->get_NumberFormat()->set_FormatCode(u"\"$\"#,##0.00");
series1->get_DataLabels()->idx_get(1)->get_NumberFormat()->set_FormatCode(u"dd/mm/yyyy");
series1->get_DataLabels()->idx_get(2)->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.
series1->get_DataLabels()->idx_get(2)->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"TestInsertAreaChart.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> labels = series0->get_DataLabels();
// Set properties.
labels->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.
labels->set_ShowLeaderLines(true);
labels->set_ShowCategoryName(false);
labels->set_ShowPercentage(false);
labels->set_ShowSeriesName(true);
labels->set_ShowValue(true);
labels->set_Separator(u"/");
labels->set_ShowValue(true);
System::String outputPath = outputDataDir + u"SimpleBarChart_out.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(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(GetAncestorInBody(startNode)) > endSection->get_Body()->IndexOf(GetAncestorInBody(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");
}
}
System::SharedPtr<Node> FindNextNode(NodeType nodeType, System::SharedPtr<Node> fromNode)
{
if (fromNode == nullptr || fromNode->get_NodeType() == nodeType)
{
return fromNode;
}
if (fromNode->get_IsComposite())
{
System::SharedPtr<Node> node = FindNextNode(nodeType, (System::DynamicCast<CompositeNode>(fromNode))->get_FirstChild());
if (node != nullptr)
{
return node;
}
}
return FindNextNode(nodeType, fromNode->get_NextSibling());
}
void ProcessMarker(System::SharedPtr<Node> cloneNode,
std::vector<System::SharedPtr<Node>> &nodes,
System::SharedPtr<Node> node,
System::SharedPtr<Node> blockLevelAncestor,
bool isInclusive,
bool isStartMarker,
bool canAdd,
bool forceAdd)
{
// If we are dealing with a block level node just see if it should be included and add it to the list.
if (node == blockLevelAncestor)
{
if (canAdd && isInclusive)
{
nodes.push_back(cloneNode);
}
return;
}
// cloneNode is a clone of blockLevelNode. If node != blockLevelNode, blockLevelAncestor is ancestor of node; that means it is a composite node.
System::Diagnostics::Debug::Assert(cloneNode->get_IsComposite());
// 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();
}
}
}
// Support a case if marker node is on the third level of document body or lower.
std::vector<System::SharedPtr<Node>> nodeBranch(FillSelfAndParents(node, blockLevelAncestor));
// Process the corresponding node in our cloned node by index.
System::SharedPtr<Node> currentCloneNode = cloneNode;
for (int index = nodeBranch.size() - 1; index >= 0; --index)
{
System::SharedPtr<Node> currentNode = nodeBranch.at(index);
int32_t nodeIndex = currentNode->get_ParentNode()->IndexOf(currentNode);
currentCloneNode = (System::DynamicCast<CompositeNode>(currentCloneNode))->get_ChildNodes()->idx_get(nodeIndex);
RemoveNodesOutsideOfRange(currentCloneNode, isInclusive || (index > 0), isStartMarker);
}
// After processing the composite node may become empty. If it has don't include it.
if (canAdd && (forceAdd || (System::DynamicCast<CompositeNode>(cloneNode))->get_HasChildNodes()))
{
nodes.push_back(cloneNode);
}
}
void IncludeNextParagraph(System::SharedPtr<Node> node, std::vector<System::SharedPtr<Node>> &nodes)
{
System::SharedPtr<Paragraph> paragraph = System::DynamicCast<Paragraph>(FindNextNode(NodeType::Paragraph, node->get_NextSibling()));
if (paragraph != nullptr)
{
// Move to first child to include paragraph without contents.
System::SharedPtr<Node> markerNode = paragraph->get_HasChildNodes() ? paragraph->get_FirstChild() : paragraph;
System::SharedPtr<Node> rootNode = GetAncestorInBody(paragraph);
ProcessMarker(rootNode->Clone(true), nodes, markerNode, rootNode, markerNode == paragraph, false, true, true);
}
}
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 (System::SharedPtr<Node> node : nodes)
{
System::SharedPtr<Node> importNode = importer->ImportNode(node, true);
dstDoc->get_FirstSection()->get_Body()->AppendChild(importNode);
}
// Return the generated document.
return dstDoc;
}
System::SharedPtr<Document> docA = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<Document> docB = System::MakeObject<Document>(inputDataDir + u"TestFile - Copy.doc");
System::SharedPtr<CompareOptions> options = System::MakeObject<CompareOptions>();
options->set_IgnoreFormatting(true);
options->set_IgnoreHeadersAndFooters(true);
options->set_IgnoreCaseChanges(true);
options->set_IgnoreTables(true);
options->set_IgnoreFields(true);
options->set_IgnoreComments(true);
options->set_IgnoreTextboxes(true);
options->set_IgnoreFootnotes(true);
// DocA now contains changes as revisions.
docA->Compare(docB, u"user", System::DateTime::get_Now(), options);
if (docA->get_Revisions()->get_Count() == 0)
{
std::cout << "Documents are equal" << std::endl;
}
else
{
std::cout << "Documents are not equal" << std::endl;
}
System::SharedPtr<Document> docA = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<Document> docB = System::MakeObject<Document>(inputDataDir + u"TestFile - Copy.doc");
System::SharedPtr<CompareOptions> options = System::MakeObject<CompareOptions>();
options->set_IgnoreFormatting(true);
// Relates to Microsoft Word "Show changes in" option in "Compare Documents" dialog box.
options->set_Target(ComparisonTargetType::New);
docA->Compare(docB, u"user", System::DateTime::get_Now(), options);
System::SharedPtr<Document> docA = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<Document> docB = System::MakeObject<Document>(inputDataDir + u"TestFile - Copy.doc");
// DocA now contains changes as revisions.
docA->Compare(docB, u"user", System::DateTime::get_Now());
if (docA->get_Revisions()->get_Count() == 0)
{
std::cout << "Documents are equal" << std::endl;
}
else
{
std::cout << "Documents are not equal" << std::endl;
}
System::SharedPtr<Document> docA = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<Document> docB = System::MakeObject<Document>(inputDataDir + u"TestFile - Copy.doc");
// DocA now contains changes as revisions.
docA->Compare(docB, u"user", System::DateTime::get_Now());
System::SharedPtr<DocumentBuilder> builderA = System::MakeObject<DocumentBuilder>(System::MakeObject<Document>());
System::SharedPtr<DocumentBuilder> builderB = System::MakeObject<DocumentBuilder>(System::MakeObject<Document>());
builderA->Writeln(u"This is A simple word");
builderB->Writeln(u"This is B simple words");
System::SharedPtr<CompareOptions> co = System::MakeObject<CompareOptions>();
co->set_Granularity(Aspose::Words::Granularity::CharLevel);
builderA->get_Document()->Compare(builderB->get_Document(), u"author", System::DateTime::get_Now(), co);
// 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));
}
}
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_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 = inputDataDir + u"Aspose.Words.gif";
builder->InsertImage(imageFileName, RelativeHorizontalPosition::Page, 10, RelativeVerticalPosition::Page, 10, 50, 50, WrapType::Through);
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Right);
// Specify another header title for other pages.
builder->Write(u"Aspose.Words Header/Footer Creation Primer.");
// --- Create footer for pages other than first. ---
builder->MoveToHeaderFooter(HeaderFooterType::FooterPrimary);
// We use table with two cells to make one part of the text on the line (with page numbering)
// To be aligned left, and the other part of the text (with copyright) to be aligned right.
builder->StartTable();
// Clear table borders.
builder->get_CellFormat()->ClearFormatting();
builder->InsertCell();
// Set first cell to 1/3 of the page width.
builder->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(100 / 3));
// Insert page numbering text here.
// It uses PAGE and NUMPAGES fields to auto calculate current page number and total number of pages.
builder->Write(u"Page ");
builder->InsertField(u"PAGE", u"");
builder->Write(u" of ");
builder->InsertField(u"NUMPAGES", u"");
// Align this text to the left.
builder->get_CurrentParagraph()->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Left);
builder->InsertCell();
// Set the second cell to 2/3 of the page width.
builder->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(100 * 2 / 3));
builder->Write(u"(C) 2001 Aspose Pty Ltd. All rights reserved.");
// Align this text to the right.
builder->get_CurrentParagraph()->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Right);
builder->EndRow();
builder->EndTable();
builder->MoveToDocumentEnd();
// Make page break to create a second page on which the primary headers/footers will be seen.
builder->InsertBreak(BreakType::PageBreak);
// Make section break to create a third page with different page orientation.
builder->InsertBreak(BreakType::SectionBreakNewPage);
// Get the new section and its page setup.
currentSection = builder->get_CurrentSection();
pageSetup = currentSection->get_PageSetup();
// Set page orientation of the new section to landscape.
pageSetup->set_Orientation(Orientation::Landscape);
// This section does not need different first page header/footer.
// We need only one title page in the document and the header/footer for this page
// Has already been defined in the previous section
pageSetup->set_DifferentFirstPageHeaderFooter(false);
// This section displays headers/footers from the previous section by default.
// Call currentSection.HeadersFooters.LinkToPrevious(false) to cancel this.
// Page width is different for the new section and therefore we need to set
// A different cell widths for a footer table.
currentSection->get_HeadersFooters()->LinkToPrevious(false);
// If we want to use the already existing header/footer set for this section
// But with some minor modifications then it may be expedient to copy headers/footers
// From the previous section and apply the necessary modifications where we want them.
CopyHeadersFootersFromPreviousSection(currentSection);
// Find the footer that we want to change.
System::SharedPtr<HeaderFooter> primaryFooter = currentSection->get_HeadersFooters()->idx_get(HeaderFooterType::FooterPrimary);
System::SharedPtr<Row> row = primaryFooter->get_Tables()->idx_get(0)->get_FirstRow();
row->get_FirstCell()->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(100 / 3));
row->get_LastCell()->get_CellFormat()->set_PreferredWidth(PreferredWidth::FromPercent(100 * 2 / 3));
System::String outputPath = outputDataDir + u"CreateHeaderFooterUsingDocBuilder.doc";
// Save the resulting document.
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"test.docx");
// Retrieve a list of all custom document properties from the file.
System::SharedPtr<CustomDocumentProperties> customProperties = doc->get_CustomDocumentProperties();
// Add linked to content property.
System::SharedPtr<DocumentProperty> customProperty = customProperties->AddLinkToContent(u"PropertyName", u"BookmarkName");
// Also, accessing the custom document property can be performed by using the property name.
customProperty = customProperties->idx_get(u"PropertyName");
// Check whether the property is linked to content.
bool isLinkedToContent = customProperty->get_IsLinkToContent();
// Get the source of the property.
System::String source = customProperty->get_LinkSource();
// Get the value of the property.
System::String value = customProperty->get_Value()->ToString();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Properties.doc");
System::SharedPtr<CustomDocumentProperties> props = doc->get_CustomDocumentProperties();
if (props->idx_get(u"Authorized") == nullptr)
{
props->Add(u"Authorized", true);
props->Add(u"Authorized By", System::String(u"John Smith"));
props->Add(u"Authorized Date", System::DateTime::get_Today());
props->Add(u"Authorized Revision", doc->get_BuiltInDocumentProperties()->get_RevisionNumber());
props->Add(u"Authorized Amount", 123.45);
}
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Properties.doc");
doc->get_CustomDocumentProperties()->Remove(u"Authorized Date");
System::String fileName = inputDataDir + u"Properties.doc";
System::SharedPtr<Document> doc = System::MakeObject<Document>(fileName);
std::cout << "1. Document name: " << fileName.ToUtf8String() << std::endl;
std::cout << "2. Built-in Properties" << std::endl;
for (System::SharedPtr<DocumentProperty> prop : System::IterateOver(doc->get_BuiltInDocumentProperties()))
{
std::cout << prop->get_Name().ToUtf8String() << " : " << prop->get_Value()->ToString().ToUtf8String() << std::endl;
}
std::cout << "3. Custom Properties" << std::endl;
for (System::SharedPtr<DocumentProperty> prop : System::IterateOver(doc->get_CustomDocumentProperties()))
{
std::cout << prop->get_Name().ToUtf8String() << " : " << prop->get_Value()->ToString().ToUtf8String() << std::endl;
}
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Properties.doc");
doc->set_RemovePersonalInformation(true);
System::String outputPath = outputDataDir + u"DocProperties.RemovePersonalInformation.docx";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Table> table = builder->StartTable();
// Insert a cell
builder->InsertCell();
// Use fixed column widths.
table->AutoFit(AutoFitBehavior::FixedColumnWidths);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"This is row 1 cell 1");
// Insert a cell
builder->InsertCell();
builder->Write(u"This is row 1 cell 2");
builder->EndRow();
// Insert a cell
builder->InsertCell();
// Apply new row formatting
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Writeln(u"This is row 2 cell 1");
// Insert a cell
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Writeln(u"This is row 2 cell 2");
builder->EndRow();
builder->EndTable();
System::String outputPath = outputDataDir + u"DocumentBuilderBuildTable.doc";
doc->Save(outputPath);
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>();
System::SharedPtr<Shape> shape = builder->InsertHorizontalRule();
System::SharedPtr<HorizontalRuleFormat> horizontalRuleFormat = shape->get_HorizontalRuleFormat();
horizontalRuleFormat->set_Alignment(HorizontalRuleAlignment::Center);
horizontalRuleFormat->set_WidthPercent(70);
horizontalRuleFormat->set_Height(3);
horizontalRuleFormat->set_Color(System::Drawing::Color::get_Blue());
horizontalRuleFormat->set_NoShade(true);
System::String outputPath = outputDataDir + u"DocumentBuilderHorizontalRule.DocumentBuilderHorizontalRuleFormat.doc";
builder->get_Document()->Save(outputPath);
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Insert a horizontal rule shape into the document.");
builder->InsertHorizontalRule();
System::String outputPath = outputDataDir + u"DocumentBuilderHorizontalRule.DocumentBuilderInsertHorizontalRule.doc";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->StartBookmark(u"FineBookmark");
builder->Writeln(u"This is just a fine bookmark.");
builder->EndBookmark(u"FineBookmark");
System::String outputPath = outputDataDir + u"DocumentBuilderInsertBookmark.doc";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"This is page 1.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"This is page 2.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"This is page 3.");
System::String outputPath = outputDataDir + u"DocumentBuilderInsertBreak.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertCheckBox(u"CheckBox", true, true, 0);
System::String outputPath = outputDataDir + u"DocumentBuilderInsertElements.InsertCheckBoxFormField.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::ArrayPtr<System::String> items = System::MakeArray<System::String>({u"One", u"Two", u"Three"});
builder->InsertComboBox(u"DropDown", items, 0);
System::String outputPath = outputDataDir + u"DocumentBuilderInsertElements.InsertComboBoxFormField.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertHtml(u"<P align='right'>Paragraph right</P><b>Implicit paragraph left</b><div align='center'>Div center</div><h1 align='left'>Heading 1 left.</h1>");
System::String outputPath = outputDataDir + u"DocumentBuilderInsertElements.InsertHtml.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertOleObject(u"http://www.aspose.com", u"htmlfile", true, true, nullptr);
System::String outputPath = outputDataDir + u"DocumentBuilderInsertElements.InsertOleObject.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a table of contents at the beginning of the document.
builder->InsertTableOfContents(u"\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder->InsertBreak(BreakType::PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 1.1");
builder->Writeln(u"Heading 1.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 2");
builder->Writeln(u"Heading 3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading3);
builder->Writeln(u"Heading 3.1.1");
builder->Writeln(u"Heading 3.1.2");
builder->Writeln(u"Heading 3.1.3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.2");
builder->Writeln(u"Heading 3.3");
doc->UpdateFields();
System::String outputPath = outputDataDir + u"DocumentBuilderInsertElements.InsertTableOfContents.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertTextInput(u"TextInput", TextFormFieldType::Regular, u"", u"Hello", 0);
System::String outputPath = outputDataDir + u"DocumentBuilderInsertElements.InsertTextInputFormField.doc";
doc->Save(outputPath);
// Load document with OLE object.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilderInsertOleObject.doc");
System::SharedPtr<Shape> oleShape = System::StaticCast<Shape>(doc->GetChild(NodeType::Shape, 0, true));
System::ByteArrayPtr oleRawData = oleShape->get_OleFormat()->GetRawData();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::ArrayPtr<uint8_t> bs = System::IO::File::ReadAllBytes(inputDataDir + u"input.zip");
System::SharedPtr<System::IO::Stream> stream = System::MakeObject<System::IO::MemoryStream>(bs);
System::SharedPtr<Shape> shape = builder->InsertOleObject(stream, u"Package", true, nullptr);
System::SharedPtr<OlePackage> olePackage = shape->get_OleFormat()->get_OlePackage();
olePackage->set_FileName(u"filename.zip");
olePackage->set_DisplayName(u"displayname.zip");
System::String outputPath = outputDataDir + u"DocumentBuilderInsertElements.InsertOleObjectwithOlePackage.doc";
doc->Save(outputPath);
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Insert a horizontal rule shape into the document.");
builder->InsertHorizontalRule();
System::String outputPath = outputDataDir + u"DocumentBuilderInsertHorizontalRule.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertImage(inputDataDir + u"Watermark.png", RelativeHorizontalPosition::Margin, 100, RelativeVerticalPosition::Margin, 100, 200, 100, WrapType::Square);
System::String outputPath = outputDataDir + u"DocumentBuilderInsertImage.InsertFloatingImage.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertImage(inputDataDir + u"Watermark.png");
System::String outputPath = outputDataDir + u"DocumentBuilderInsertImage.InsertInlineImage.doc";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Specify font formatting
System::SharedPtr<Font> font = builder->get_Font();
font->set_Size(16);
font->set_Bold(true);
font->set_Color(System::Drawing::Color::get_Blue());
font->set_Name(u"Arial");
font->set_Underline(Underline::Dash);
// Specify paragraph formatting
System::SharedPtr<ParagraphFormat> paragraphFormat = builder->get_ParagraphFormat();
paragraphFormat->set_FirstLineIndent(8);
paragraphFormat->set_Alignment(ParagraphAlignment::Justify);
paragraphFormat->set_KeepTogether(true);
builder->Writeln(u"A whole paragraph.");
System::String outputPath = outputDataDir + u"DocumentBuilderInsertParagraph.doc";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Create a document builder to insert content with.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a TC field at the current document builder position.
builder->InsertField(u"TC \"Entry Text\" \\f t");
System::String outputPath = outputDataDir + u"DocumentBuilderInsertTCField.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
// Highlight newly inserted content.
options->get_ApplyFont()->set_HighlightColor(System::Drawing::Color::get_DarkOrange());
options->set_ReplacingCallback(System::MakeObject<InsertTCFieldHandler>(u"Chapter 1", u"\\l 1"));
// Insert a TC field which displays "Chapter 1" just before the text "The Beginning" in the document.
doc->get_Range()->Replace(System::MakeObject<System::Text::RegularExpressions::Regex>(u"The Beginning"), u"", options);
class InsertTCFieldHandler : public IReplacingCallback
{
typedef InsertTCFieldHandler ThisType;
typedef IReplacingCallback BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
public:
InsertTCFieldHandler(const System::String& text, const System::String& switches)
: mFieldText(text), mFieldSwitches(switches) {}
InsertTCFieldHandler(const System::String& switches)
: mFieldText(System::String::Empty), mFieldSwitches(switches) {}
ReplaceAction Replacing(System::SharedPtr<ReplacingArgs> args) override;
private:
System::String mFieldText;
System::String mFieldSwitches;
};
ReplaceAction InsertTCFieldHandler::Replacing(System::SharedPtr<ReplacingArgs> args)
{
// Create a builder to insert the field.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(System::DynamicCast<Document>(args->get_MatchNode()->get_Document()));
// Move to the first node of the match.
builder->MoveTo(args->get_MatchNode());
// If the user specified text to be used in the field as display text then use that, otherwise use the
// Match string as the display text.
System::String insertText;
if (!System::String::IsNullOrEmpty(mFieldText))
{
insertText = mFieldText;
}
else
{
insertText = args->get_Match()->get_Value();
}
// Insert the TC field before this node using the specified string as the display text and user defined switches.
builder->InsertField(System::String::Format(u"TC \"{0}\" {1}", insertText, mFieldSwitches));
// We have done what we want so skip replacement.
return ReplaceAction::Skip;
}
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a table of contents at the beginning of the document.
builder->InsertTableOfContents(u"\\o \"1-3\" \\h \\z \\u");
// The newly inserted table of contents will be initially empty.
// It needs to be populated by updating the fields in the document.
doc->UpdateFields();
System::String outputPath = outputDataDir + u"DocumentBuilderInsertTOC.doc";
doc->Save(outputPath);
// Shows how to access the current node in a document builder.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Node> curNode = builder->get_CurrentNode();
System::SharedPtr<Paragraph> curParagraph = builder->get_CurrentParagraph();
// Create a blank document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Specify that we want headers and footers different for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header First");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header Even");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header Odd");
// Create three pages in the document.
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page3");
System::String outputPath = outputDataDir + u"DocumentBuilderMovingCursor.HeadersAndFooters.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToBookmark(u"CoolBookmark");
builder->Writeln(u"This is a very cool bookmark.");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToBookmark(u"CoolBookmark", false, true);
builder->Writeln(u"This is a very cool bookmark.");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToDocumentEnd();
std::cout << "This is the end of the document." << std::endl;
builder->MoveToDocumentStart();
std::cout << "This is the beginning of the document." << std::endl;
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToMergeField(u"NiceMergeField");
builder->Writeln(u"This is a very nice merge field.");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_LastParagraph());
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Parameters are 0-index. Moves to third paragraph.
builder->MoveToParagraph(2, 0);
builder->Writeln(u"This is the 3rd paragraph.");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Parameters are 0-index. Moves to third section.
builder->MoveToSection(2);
builder->Writeln(u"This is the 3rd section.");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"DocumentBuilder.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// All parameters are 0-index. Moves to the 2nd table, 3rd row, 5th cell.
builder->MoveToCell(1, 2, 4, 0);
builder->Writeln(u"Hello World!");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Input.docx");
System::SharedPtr<ParagraphFormat> format = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ParagraphFormat();
format->set_CharacterUnitLeftIndent(10);
// ParagraphFormat.LeftIndent will be updated
format->set_CharacterUnitRightIndent(10);
// ParagraphFormat.RightIndent will be updated
format->set_CharacterUnitFirstLineIndent(20);
// ParagraphFormat.FirstLineIndent will be updated
format->set_LineUnitBefore(5);
// ParagraphFormat.SpaceBefore will be updated
format->set_LineUnitAfter(10);
// ParagraphFormat.SpaceAfter will be updated
const System::String outputPath = outputDataDir + u"ChangeAsianParagraphSpacingAndIndents_out.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set paragraph borders
System::SharedPtr<BorderCollection> borders = builder->get_ParagraphFormat()->get_Borders();
borders->set_DistanceFromText(20);
borders->idx_get(BorderType::Left)->set_LineStyle(LineStyle::Double);
borders->idx_get(BorderType::Right)->set_LineStyle(LineStyle::Double);
borders->idx_get(BorderType::Top)->set_LineStyle(LineStyle::Double);
borders->idx_get(BorderType::Bottom)->set_LineStyle(LineStyle::Double);
// Set paragraph shading
System::SharedPtr<Shading> shading = builder->get_ParagraphFormat()->get_Shading();
shading->set_Texture(TextureIndex::TextureDiagonalCross);
shading->set_BackgroundPatternColor(System::Drawing::Color::get_LightCoral());
shading->set_ForegroundPatternColor(System::Drawing::Color::get_LightSalmon());
builder->Write(u"I'm a formatted paragraph with double border and nice shading.");
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.ApplyBordersAndShadingToParagraph.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set paragraph style
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Title);
builder->Write(u"Hello");
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.ApplyParagraphStyle.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set font formatting properties
System::SharedPtr<Font> font = builder->get_Font();
font->set_Bold(true);
font->set_Color(System::Drawing::Color::get_DarkBlue());
font->set_Italic(true);
font->set_Name(u"Arial");
font->set_Size(24);
font->set_Spacing(5);
font->set_Underline(Underline::Double);
// Output formatted text
builder->Writeln(u"I'm a very nice formatted string.");
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.SetFontFormatting.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->get_ListFormat()->ApplyNumberDefault();
builder->Writeln(u"Item 1");
builder->Writeln(u"Item 2");
builder->get_ListFormat()->ListIndent();
builder->Writeln(u"Item 2.1");
builder->Writeln(u"Item 2.2");
builder->get_ListFormat()->ListIndent();
builder->Writeln(u"Item 2.2.1");
builder->Writeln(u"Item 2.2.2");
builder->get_ListFormat()->ListOutdent();
builder->Writeln(u"Item 2.3");
builder->get_ListFormat()->ListOutdent();
builder->Writeln(u"Item 3");
builder->get_ListFormat()->RemoveNumbers();
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.SetMultilevelListFormatting.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set page properties
builder->get_PageSetup()->set_Orientation(Orientation::Landscape);
builder->get_PageSetup()->set_LeftMargin(50);
builder->get_PageSetup()->set_PaperSize(PaperSize::Paper10x14);
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.SetPageSetupAndSectionFormatting.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set paragraph formatting properties
System::SharedPtr<ParagraphFormat> paragraphFormat = builder->get_ParagraphFormat();
paragraphFormat->set_Alignment(ParagraphAlignment::Center);
paragraphFormat->set_LeftIndent(50);
paragraphFormat->set_RightIndent(50);
paragraphFormat->set_SpaceAfter(25);
// Output text
builder->Writeln(u"I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
builder->Writeln(u"I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.SetParagraphFormatting.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Set paragraph formatting properties
System::SharedPtr<ParagraphFormat> paragraphFormat = builder->get_ParagraphFormat();
paragraphFormat->set_AddSpaceBetweenFarEastAndAlpha(true);
paragraphFormat->set_AddSpaceBetweenFarEastAndDigit(true);
builder->Writeln(u"Automatically adjust space between Asian and Latin text");
builder->Writeln(u"Automatically adjust space between Asian text and numbers");
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.SetSpacebetweenAsianandLatintext.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->StartTable();
builder->InsertCell();
// Set the cell formatting
System::SharedPtr<CellFormat> cellFormat = builder->get_CellFormat();
cellFormat->set_Width(250);
cellFormat->set_LeftPadding(30);
cellFormat->set_RightPadding(30);
cellFormat->set_TopPadding(30);
cellFormat->set_BottomPadding(30);
builder->Writeln(u"I'm a wonderful formatted cell.");
builder->EndRow();
builder->EndTable();
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.SetTableCellFormatting.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
// Set the row formatting
System::SharedPtr<RowFormat> rowFormat = builder->get_RowFormat();
rowFormat->set_Height(100);
rowFormat->set_HeightRule(HeightRule::Exactly);
// These formatting properties are set on the table and are applied to all rows in the table.
table->set_LeftPadding(30);
table->set_RightPadding(30);
table->set_TopPadding(30);
table->set_BottomPadding(30);
builder->Writeln(u"I'm a wonderful formatted row.");
builder->EndRow();
builder->EndTable();
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.SetTableRowFormatting.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Input.docx");
System::SharedPtr<ParagraphFormat> format = doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_ParagraphFormat();
format->set_FarEastLineBreakControl(false);
format->set_WordWrap(true);
format->set_HangingPunctuation(false);
System::String outputPath = outputDataDir + u"DocumentBuilderSetFormatting.SetAsianTypographyLinebreakGroupProp.docx";
doc->Save(outputPath);
auto document = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(document);
builder->get_Font()->set_EmphasisMark(EmphasisMark::UnderSolidCircle);
builder->Write(u"Emphasis text");
builder->Writeln();
builder->get_Font()->ClearFormatting();
builder->Write(u"Simple text");
document->Save(outputDataDir + u"FontEmphasisMark_out.doc");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Input.docx");
System::SharedPtr<Paragraph> par = doc->get_FirstSection()->get_Body()->get_FirstParagraph();
par->get_ParagraphFormat()->set_SnapToGrid(true);
par->get_Runs()->idx_get(0)->get_Font()->set_SnapToGrid(true);
const System::String outputPath = outputDataDir + u"SetSnapToGrid_out.doc";
doc->Save(outputPath);
// 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");
//Set the layout mode for a section allowing to define the document grid behavior
//Note that the Document Grid tab becomes visible in the Page Setup dialog of MS Word if any Asian language is defined as editing language.
doc->get_FirstSection()->get_PageSetup()->set_LayoutMode(SectionLayoutMode::Grid);
//Set the number of characters per line in the document grid.
doc->get_FirstSection()->get_PageSetup()->set_CharactersPerLine(30);
//Set the number of lines per page in the document grid.
doc->get_FirstSection()->get_PageSetup()->set_LinesPerPage(10);
System::String outputPath = outputDataDir + u"DocumentPageSetup.doc";
doc->Save(outputPath);
// 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"TestFile.doc");
System::SharedPtr<Paragraph> startPara = System::DynamicCast<Paragraph>(doc->get_LastSection()->GetChild(NodeType::Paragraph, 2, true));
System::SharedPtr<Table> endTable = System::DynamicCast<Table>(doc->get_LastSection()->GetChild(NodeType::Table, 0, true));
// Extract the content between these nodes in the document. Include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startPara, endTable, true);
// Lets reverse the array to make inserting the content back into the document easier.
for (auto it = extractedNodes.rbegin(); it != extractedNodes.rend(); ++it)
{
endTable->get_ParentNode()->InsertAfter(*it, endTable);
}
System::String outputPath = outputDataDir + u"ExtractContentBetweenBlockLevelNodes.doc";
// Save the generated document to disk.
doc->Save(outputPath);
// 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"TestFile.doc");
System::SharedPtr<Section> section = doc->get_Sections()->idx_get(0);
section->get_PageSetup()->set_LeftMargin(70.85);
// Retrieve the bookmark from the document.
System::SharedPtr<Bookmark> bookmark = doc->get_Range()->get_Bookmarks()->idx_get(u"Bookmark1");
// We use the BookmarkStart and BookmarkEnd nodes as markers.
System::SharedPtr<BookmarkStart> bookmarkStart = bookmark->get_BookmarkStart();
System::SharedPtr<BookmarkEnd> bookmarkEnd = bookmark->get_BookmarkEnd();
// Firstly extract the content between these nodes including the bookmark.
TNodePtrVector extractedNodesInclusive = ExtractContent(bookmarkStart, bookmarkEnd, true);
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodesInclusive);
System::String inclusiveOutputPath = outputDataDir + u"ExtractContentBetweenBookmark.Inclusive.doc";
dstDoc->Save(inclusiveOutputPath);
std::cout << "File saved at " << inclusiveOutputPath.ToUtf8String() << std::endl;
// Secondly extract the content between these nodes this time without including the bookmark.
TNodePtrVector extractedNodesExclusive = ExtractContent(bookmarkStart, bookmarkEnd, false);
dstDoc = GenerateDocument(doc, extractedNodesExclusive);
System::String exclusiveOutputPath = outputDataDir + u"ExtractContentBetweenBookmark.Exclusive.doc";
dstDoc->Save(exclusiveOutputPath);
std::cout << "File saved at " << exclusiveOutputPath.ToUtf8String() << 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"TestFile.doc");
// This is a quick way of getting both comment nodes.
// Your code should have a proper method of retrieving each corresponding start and end node.
System::SharedPtr<CommentRangeStart> commentStart = System::DynamicCast<CommentRangeStart>(doc->GetChild(NodeType::CommentRangeStart, 0, true));
System::SharedPtr<CommentRangeEnd> commentEnd = System::DynamicCast<CommentRangeEnd>(doc->GetChild(NodeType::CommentRangeEnd, 0, true));
// Firstly extract the content between these nodes including the comment as well.
TNodePtrVector extractedNodesInclusive = ExtractContent(commentStart, commentEnd, true);
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodesInclusive);
System::String inclusiveOutputPath = outputDataDir + u"ExtractContentBetweenCommentRange.Inclusive.doc";
dstDoc->Save(inclusiveOutputPath);
std::cout << "File saved at " << inclusiveOutputPath.ToUtf8String() << std::endl;
// Secondly extract the content between these nodes without the comment.
TNodePtrVector extractedNodesExclusive = ExtractContent(commentStart, commentEnd, false);
dstDoc = GenerateDocument(doc, extractedNodesExclusive);
System::String exclusiveOutputPath = outputDataDir + u"ExtractContentBetweenCommentRange.Exclusive.doc";
dstDoc->Save(exclusiveOutputPath);
std::cout << "File saved at " << exclusiveOutputPath.ToUtf8String() << 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"TestFile.doc");
// Gather the nodes. The GetChild method uses 0-based index
System::SharedPtr<Paragraph> startPara = System::DynamicCast<Paragraph>(doc->get_FirstSection()->get_Body()->GetChild(NodeType::Paragraph, 6, true));
System::SharedPtr<Paragraph> endPara = System::DynamicCast<Paragraph>(doc->get_FirstSection()->get_Body()->GetChild(NodeType::Paragraph, 10, true));
// Extract the content between these nodes in the document. Include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startPara, endPara, true);
// Insert the content into a new separate document and save it to disk.
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodes);
System::String outputPath = outputDataDir + u"ExtractContentBetweenParagraphs.doc";
dstDoc->Save(outputPath);
// 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"TestFile.doc");
// Gather a list of the paragraphs using the respective heading styles.
TParagraphPtrVector parasStyleHeading1 = ParagraphsByStyleName(doc, u"Heading 1");
TParagraphPtrVector parasStyleHeading3 = ParagraphsByStyleName(doc, u"Heading 3");
// Use the first instance of the paragraphs with those styles.
System::SharedPtr<Node> startPara1 = parasStyleHeading1[0];
System::SharedPtr<Node> endPara1 = parasStyleHeading3[0];
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startPara1, endPara1, false);
// Insert the content into a new separate document and save it to disk.
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodes);
System::String outputPath = outputDataDir + u"ExtractContentBetweenParagraphStyles.doc";
dstDoc->Save(outputPath);
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Retrieve a paragraph from the first section.
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 7, true));
// Use some runs for extraction.
System::SharedPtr<Run> startRun = para->get_Runs()->idx_get(1);
System::SharedPtr<Run> endRun = para->get_Runs()->idx_get(4);
// Extract the content between these nodes in the document. Include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startRun, endRun, true);
// Get the node from the list. There should only be one paragraph returned in the list.
System::SharedPtr<Node> node = extractedNodes[0];
// Print the text of this node to the console.
std::cout << node->ToString(SaveFormat::Text).ToUtf8String() << std::endl;
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
// Open the document we want to convert.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Visitor.ToText.doc");
// Create an object that inherits from the DocumentVisitor class.
System::SharedPtr<MyDocToTxtWriter> myConverter = System::MakeObject<MyDocToTxtWriter>();
// This is the well known Visitor pattern. Get the model to accept a visitor.
// The model will iterate through itself by calling the corresponding methods
// On the visitor object (this is called visiting).
// Note that every node in the object model has the Accept method so the visiting
// Can be executed not only for the whole document, but for any node in the document.
doc->Accept(myConverter);
// Once the visiting is complete, we can retrieve the result of the operation,
// That in this example, has accumulated in the visitor.
std::cout << myConverter->GetText().ToUtf8String() << 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"TestFile.doc");
// Use a document builder to retrieve the field start of a merge field.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field.
// We could also get FieldStarts of a field using GetChildNode method as in the other examples.
builder->MoveToMergeField(u"Fullname", false, false);
// The builder cursor should be positioned at the start of the field.
System::SharedPtr<FieldStart> startField = System::DynamicCast<FieldStart>(builder->get_CurrentNode());
System::SharedPtr<Paragraph> endPara = System::DynamicCast<Paragraph>(doc->get_FirstSection()->GetChild(NodeType::Paragraph, 5, true));
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startField, endPara, false);
// Insert the content into a new separate document and save it to disk.
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodes);
System::String outputPath = outputDataDir + u"ExtractContentUsingField.doc";
dstDoc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Enter a dummy field into the document.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD Field");
// GetText will retrieve all field codes and special characters
std::cout << "GetText() Result: " << doc->GetText().ToUtf8String() << std::endl;
// ToString will export the node to the specified format. When converted to text it will not retrieve fields code
// Or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
// This is the same as "viewing" the document as if it was opened in a text editor.
std::cout << "ToString() Result: " << doc->ToString(SaveFormat::Text).ToUtf8String() << std::endl;
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->get_Font()->set_Name(u"Calibri");
builder->Writeln(u"qText");
// Obtain line spacing.
System::SharedPtr<Font> font = builder->get_Document()->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0)->get_Font();
//Console.WriteLine($"lineSpacing = {font.LineSpacing}");
std::cout << "lineSpacing = " << font->get_LineSpacing() << std::endl;
// 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");
System::String variables = u"";
for (System::Collections::Generic::KeyValuePair<System::String, System::String> entry : System::IterateOver(doc->get_Variables()))
{
System::String name = entry.get_Key();
System::String value = entry.get_Value();
if (variables == u"")
{
// Do something useful.
variables = System::String(u"Name: ") + name + u"," + u"Value: " + value;
}
else
{
variables = variables + u"Name: " + name + u"," + u"Value: " + value;
}
}
/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// Should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
void InsertDocument(System::SharedPtr<Node> insertAfterNode, const System::SharedPtr<Document>& srcDoc)
{
// Make sure that the node is either a paragraph or table.
if (insertAfterNode->get_NodeType() != NodeType::Paragraph && insertAfterNode->get_NodeType() != NodeType::Table)
{
throw System::ArgumentException(u"The destination node should be either a paragraph or table.");
}
// We will be inserting into the parent of the destination paragraph.
System::SharedPtr<CompositeNode> dstStory = insertAfterNode->get_ParentNode();
// This object will be translating styles and lists during the import.
System::SharedPtr<NodeImporter> importer = System::MakeObject<NodeImporter>(srcDoc, insertAfterNode->get_Document(), ImportFormatMode::KeepSourceFormatting);
// Loop through all sections in the source document.
for (System::SharedPtr<Section> srcSection : System::IterateOver<System::SharedPtr<Section>>(srcDoc->get_Sections()))
{
// Loop through all block level nodes (paragraphs and tables) in the body of the section.
for (System::SharedPtr<Node> srcNode : System::IterateOver(srcSection->get_Body()))
{
// Let's skip the node if it is a last empty paragraph in a section.
if (srcNode->get_NodeType() == NodeType::Paragraph)
{
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(srcNode);
if (para->get_IsEndOfSection() && !para->get_HasChildNodes())
{
continue;
}
}
// This creates a clone of the node, suitable for insertion into the destination document.
System::SharedPtr<Node> newNode = importer->ImportNode(srcNode, true);
// Insert new node after the reference node.
dstStory->InsertAfter(newNode, insertAfterNode);
insertAfterNode = newNode;
}
}
}
System::SharedPtr<Document> mainDoc = System::MakeObject<Document>(inputDataDir + u"InsertDocument1.doc");
System::SharedPtr<Document> subDoc = System::MakeObject<Document>(inputDataDir + u"InsertDocument2.doc");
System::SharedPtr<Bookmark> bookmark = mainDoc->get_Range()->get_Bookmarks()->idx_get(u"insertionPlace");
InsertDocument(bookmark->get_BookmarkStart()->get_ParentNode(), subDoc);
System::String outputPath = outputDataDir + u"InsertDoc.InsertDocumentAtBookmark.doc";
mainDoc->Save(outputPath);
// Open the main document.
typedef System::SharedPtr<System::Object> TObjectPtr;
System::SharedPtr<Document> mainDoc = System::MakeObject<Document>(inputDataDir + u"InsertDocument1.doc");
// Add a handler to MergeField event
mainDoc->get_MailMerge()->set_FieldMergingCallback(System::MakeObject<InsertDocumentAtMailMergeHandler>());
// The main document has a merge field in it called "Document_1".
// The corresponding data for this field contains fully qualified path to the document
// That should be inserted to this field.
mainDoc->get_MailMerge()->Execute(System::MakeArray<System::String>({u"Document_1"}), System::StaticCastArray<TObjectPtr>(System::MakeArray<System::String>({inputDataDir + u"InsertDocument2.doc"})));
System::String outputPath = outputDataDir + u"InsertDoc.InsertDocumentAtMailMerge.doc";
mainDoc->Save(outputPath);
System::SharedPtr<Document> mainDoc = System::MakeObject<Document>(inputDataDir + u"InsertDocument1.doc");
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
options->set_ReplacingCallback(System::MakeObject<InsertDocumentAtReplaceHandler>());
mainDoc->get_Range()->Replace(System::MakeObject<System::Text::RegularExpressions::Regex>(u"\\[MY_DOCUMENT\\]"), u"", options);
System::String outputPath = outputDataDir + u"InsertDoc.InsertDocumentAtReplace.doc";
mainDoc->Save(outputPath);
class InsertDocumentAtReplaceHandler : public IReplacingCallback
{
typedef InsertDocumentAtReplaceHandler ThisType;
typedef IReplacingCallback BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
public:
ReplaceAction Replacing(System::SharedPtr<ReplacingArgs> e) override;
};
ReplaceAction InsertDocumentAtReplaceHandler::Replacing(System::SharedPtr<ReplacingArgs> e)
{
System::SharedPtr<Document> subDoc = System::MakeObject<Document>(GetInputDataDir_WorkingWithDocument() + u"InsertDocument2.doc");
// Insert a document after the paragraph, containing the match text.
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(e->get_MatchNode()->get_ParentNode());
InsertDocument(para, subDoc);
// Remove the paragraph with the match text.
para->Remove();
return ReplaceAction::Skip;
}
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_RenderingAndPrinting();
// Initialize document.
System::String fileName = u"TestFile.doc";
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + fileName);
for (System::SharedPtr<Paragraph> paragraph : System::IterateOver<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)))
{
if (paragraph->get_BreakIsStyleSeparator())
{
std::cout << "Separator Found!" << std::endl;
}
}
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputFileName);
ProtectionType protectionType = doc->get_ProtectionType();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputFileName);
doc->Protect(ProtectionType::AllowOnlyFormFields, u"password");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputFileName);
doc->Unprotect();
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
void RemovePageBreaks(const System::SharedPtr<Document>& doc)
{
// Retrieve all paragraphs in the document.
System::SharedPtr<NodeCollection> paragraphs = doc->GetChildNodes(NodeType::Paragraph, true);
// Iterate through all paragraphs
for (System::SharedPtr<Paragraph> para : System::IterateOver<System::SharedPtr<Paragraph>>(paragraphs))
{
// If the paragraph has a page break before set then clear it.
if (para->get_ParagraphFormat()->get_PageBreakBefore())
{
para->get_ParagraphFormat()->set_PageBreakBefore(false);
}
// Check all runs in the paragraph for page breaks and remove them.
for (System::SharedPtr<Run> run : System::IterateOver<System::SharedPtr<Run>>(para->get_Runs()))
{
if (run->get_Text().Contains(ControlChar::PageBreak()))
{
run->set_Text(run->get_Text().Replace(ControlChar::PageBreak(), System::String::Empty));
}
}
}
}
void RemoveSectionBreaks(const System::SharedPtr<Document>& doc)
{
// Loop through all sections starting from the section that precedes the last one
// And moving to the first section.
for (int32_t i = doc->get_Sections()->get_Count() - 2; i >= 0; i--)
{
// Copy the content of the current section to the beginning of the last section.
doc->get_LastSection()->PrependContent(doc->get_Sections()->idx_get(i));
// Remove the copied section.
doc->get_Sections()->idx_get(i)->Remove();
}
}
// 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"HeaderFooter.RemoveFooters.doc");
for (System::SharedPtr<Section> section : System::IterateOver<System::SharedPtr<Section>>(doc))
{
// Up to three different footers are possible in a section (for first, even and odd pages).
// We check and delete all of them.
System::SharedPtr<HeaderFooter> footer;
footer = section->get_HeadersFooters()->idx_get(HeaderFooterType::FooterFirst);
if (footer != nullptr)
{
footer->Remove();
}
// Primary footer is the footer used for odd pages.
footer = section->get_HeadersFooters()->idx_get(HeaderFooterType::FooterPrimary);
if (footer != nullptr)
{
footer->Remove();
}
footer = section->get_HeadersFooters()->idx_get(HeaderFooterType::FooterEven);
if (footer != nullptr)
{
footer->Remove();
}
}
System::String outputPath = outputDataDir + u"RemoveFooters.doc";
// Save the document.
doc->Save(outputPath);
/// <summary>
/// Removes the specified table of contents field from the document.
/// </summary>
/// <param name="doc">The document to remove the field from.</param>
/// <param name="index">The zero-based index of the TOC to remove.</param>
void RemoveTableOfContents(const System::SharedPtr<Document>& doc, int32_t index)
{
// Store the FieldStart nodes of TOC fields in the document for quick access.
std::vector<System::SharedPtr<FieldStart>> fieldStarts;
// This is a list to store the nodes found inside the specified TOC. They will be removed
// At the end of this method.
std::vector<System::SharedPtr<Node>> nodeList;
for (System::SharedPtr<FieldStart> start : System::IterateOver<System::SharedPtr<FieldStart>>(doc->GetChildNodes(NodeType::FieldStart, true)))
{
if (start->get_FieldType() == FieldType::FieldTOC)
{
// Add all FieldStarts which are of type FieldTOC.
fieldStarts.push_back(start);
}
}
// Ensure the TOC specified by the passed index exists.
if (index > fieldStarts.size() - 1)
{
throw System::ArgumentOutOfRangeException(u"TOC index is out of range");
}
bool isRemoving = true;
// Get the FieldStart of the specified TOC.
System::SharedPtr<Node> currentNode = fieldStarts[index];
while (isRemoving)
{
// It is safer to store these nodes and delete them all at once later.
nodeList.push_back(currentNode);
currentNode = currentNode->NextPreOrder(doc);
// Once we encounter a FieldEnd node of type FieldTOC then we know we are at the end
// Of the current TOC and we can stop here.
if (currentNode->get_NodeType() == NodeType::FieldEnd)
{
System::SharedPtr<FieldEnd> fieldEnd = System::DynamicCast<FieldEnd>(currentNode);
if (fieldEnd->get_FieldType() == FieldType::FieldTOC)
{
isRemoving = false;
}
}
}
// Remove all nodes found in the specified TOC.
for (System::SharedPtr<Node> node : nodeList)
{
node->Remove();
}
}
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithStyles();
System::String outputDataDir = GetOutputDataDir_WorkingWithStyles();
// Open a document which contains a TOC.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.TableOfContents.doc");
// Remove the first table of contents from the document.
RemoveTableOfContents(doc, 0);
System::String outputPath = outputDataDir + u"RemoveTOCFromDocument.doc";
// Save the output.
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<StructuredDocumentTag> sdtRichText = System::MakeObject<StructuredDocumentTag>(doc, SdtType::RichText, MarkupLevel::Block);
System::SharedPtr<Paragraph> para = System::MakeObject<Paragraph>(doc);
System::SharedPtr<Run> run = System::MakeObject<Run>(doc);
run->set_Text(u"Hello World");
run->get_Font()->set_Color(System::Drawing::Color::get_Green());
para->get_Runs()->Add(run);
sdtRichText->get_ChildNodes()->Add(para);
doc->get_FirstSection()->get_Body()->AppendChild(sdtRichText);
System::String outputPath = outputDataDir + u"RichTextBoxContentControl.docx";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.docx");
doc->get_CompatibilityOptions()->OptimizeFor(MsWordVersion::Word2016);
System::String outputPath = outputDataDir + u"SetCompatibilityOptions.docx";
// Save the document to disk.
doc->Save(outputPath);
// Create a new LoadOptions object.
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
// Set language preferences that will be used when document is loading.
loadOptions->get_LanguagePreferences()->AddEditingLanguage(EditingLanguage::Japanese);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"languagepreferences.docx", loadOptions);
// The path to the documents directory.
System::SharedPtr<LoadOptions> loadOptions = System::MakeObject<LoadOptions>();
loadOptions->get_LanguagePreferences()->set_DefaultEditingLanguage(EditingLanguage::Russian);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"languagepreferences.docx", loadOptions);
int32_t localeId = doc->get_Styles()->get_DefaultFont()->get_LocaleId();
if (localeId == static_cast<int32_t>(EditingLanguage::Russian))
{
std::cout << "The document either has no any language set in defaults or it was set to Russian originally." << std::endl;
}
else
{
std::cout << "The document default language was set to another than Russian language originally, so it is not overridden." << std::endl;
}
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Load the template document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Set view option.
doc->get_ViewOptions()->set_ViewType(ViewType::PageLayout);
doc->get_ViewOptions()->set_ZoomPercent(50);
System::String outputPath = outputDataDir + u"SetViewOption.doc";
// Save the finished document.
doc->Save(outputPath);
auto doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
doc->set_ShowGrammaticalErrors(true);
doc->set_ShowSpellingErrors(true);
auto outputPath = outputDataDir + u"ShowGrammaticalAndSpellingErrors.docx";
doc->Save(outputPath);
// Create a new resulting document
auto mergedDoc = System::MakeObject<Document>();
auto mergedDocBuilder = System::MakeObject<DocumentBuilder>(mergedDoc);
// Merge document parts one by one
for (int idx = 1; idx <= 13; idx++)
{
System::String documentPath = inputDataDir + u"SplitDocumentPageByPageOut_" + System::Convert::ToString(idx) + u".docx";
auto sourceDoc = System::MakeObject<Document>(documentPath);
mergedDocBuilder->MoveToDocumentEnd();
mergedDocBuilder->InsertDocument(sourceDoc, ImportFormatMode::KeepSourceFormatting);
}
mergedDoc->Save(outputDataDir + u"MergeDocuments_out.docx");
// Open a Word document
auto doc = System::MakeObject<Document>(inputDataDir + u"TestFile (Split).docx");
// Split nodes in the document into separate pages
DocumentPageSplitter splitter(doc);
// Get part of the document
auto pageDoc = splitter.GetDocumentOfPageRange(3, 6);
pageDoc->Save(outputDataDir + u"SplitDocumentByPageRangeOut.docx");
// Open a Word document
auto doc = System::MakeObject<Document>(inputDataDir + u"TestFile (Split).docx");
for (int i = 0; i < doc->get_Sections()->get_Count(); i++)
{
// Split a document into smaller parts, in this instance split by section
auto section = doc->get_Sections()->idx_get(i)->Clone();
auto newDoc = System::MakeObject<Document>();
newDoc->get_Sections()->Clear();
auto newSection = System::StaticCast<Section>(newDoc->ImportNode(section, true));
newDoc->get_Sections()->Add(newSection);
// Save each section as a separate document
newDoc->Save(outputDataDir + u"SplitDocumentBySectionsOut_" + System::Convert::ToString(i) + u".docx");
}
// Open a Word document
auto doc = System::MakeObject<Document>(inputDataDir + u"TestFile (Split).docx");
// Split nodes in the document into separate pages
DocumentPageSplitter splitter(doc);
// Save each page as a separate document
for (int page = 1; page <= doc->get_PageCount(); page++)
{
auto pageDoc = splitter.GetDocumentOfPage(page);
pageDoc->Save(outputDataDir + u"SplitDocumentPageByPageOut_" + System::Convert::ToString(page) + u".docx");
}
// Open an existing document
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"CheckBoxTypeContentControl.docx");
for (System::SharedPtr<StructuredDocumentTag> sdt : System::IterateOver<System::SharedPtr<StructuredDocumentTag>>(doc->GetChildNodes(NodeType::StructuredDocumentTag, true)))
{
if (sdt->get_SdtType() == SdtType::PlainText)
{
sdt->RemoveAllChildren();
System::SharedPtr<Paragraph> para = System::DynamicCast_noexcept<Paragraph>(sdt->AppendChild(System::MakeObject<Paragraph>(doc)));
System::SharedPtr<Run> run = System::MakeObject<Run>(doc, u"new text goes here");
para->AppendChild(run);
}
else if (sdt->get_SdtType() == SdtType::DropDownList)
{
System::SharedPtr<SdtListItem> secondItem = sdt->get_ListItems()->idx_get(2);
sdt->get_ListItems()->set_SelectedValue(secondItem);
}
else if (sdt->get_SdtType() == SdtType::Picture)
{
System::SharedPtr<Shape> shape = System::DynamicCast<Shape>(sdt->GetChild(NodeType::Shape, 0, true));
if (shape->get_HasImage())
{
shape->get_ImageData()->SetImage(inputDataDir + u"Watermark.png");
}
}
}
System::String outputPath = outputDataDir + u"UpdateContentControls.ModifyContentControls.docx";
doc->Save(outputPath);
// Open an existing document
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"CheckBoxTypeContentControl.docx");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Get the first content control from the document
System::SharedPtr<StructuredDocumentTag> SdtCheckBox = System::DynamicCast<StructuredDocumentTag>(doc->GetChild(NodeType::StructuredDocumentTag, 0, true));
// StructuredDocumentTag.Checked property gets/sets current state of the Checkbox SDT
if (SdtCheckBox->get_SdtType() == SdtType::Checkbox)
{
SdtCheckBox->set_Checked(true);
}
System::String outputPath = outputDataDir + u"UpdateContentControls.SetCurrentStateOfCheckBox.docx";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.docx");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Write(u"Some text");
builder->InsertFootnote(FootnoteType::Endnote, u"Eootnote text.");
System::SharedPtr<EndnoteOptions> option = doc->get_EndnoteOptions();
option->set_RestartRule(FootnoteNumberingRule::RestartPage);
option->set_Position(EndnotePosition::EndOfSection);
System::String outputPath = outputDataDir + u"WorkingWithFootnote.SetEndnoteOptions.docx";
// Save the document to disk.
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.docx");
//Set footnote and endnode position.
doc->get_FootnoteOptions()->set_Position(FootnotePosition::BeneathText);
doc->get_EndnoteOptions()->set_Position(EndnotePosition::EndOfSection);
System::String outputPath = outputDataDir + u"WorkingWithFootnote.SetFootnoteAndEndNotePosition.docx";
// Save the document to disk.
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.docx");
//Specify the number of columns with which the footnotes area is formatted.
doc->get_FootnoteOptions()->set_Columns(3);
System::String outputPath = outputDataDir + u"WorkingWithFootnote.SetFootNoteColumns.docx";
// Save the document to disk.
doc->Save(outputPath);
auto srcDoc = System::MakeObject<Document>(inputDataDir + u"source.docx");
auto dstDoc = System::MakeObject<Document>(inputDataDir + u"destination.docx");
auto options = System::MakeObject<ImportFormatOptions>();
// Keep the source text boxes formatting when importing.
options->set_IgnoreTextBoxes(false);
auto importer = System::MakeObject<NodeImporter>(srcDoc, dstDoc, ImportFormatMode::KeepSourceFormatting, options);
auto srcParas = srcDoc->get_FirstSection()->get_Body()->get_Paragraphs();
for (const auto& srcPara : System::IterateOver<Paragraph>(srcParas))
{
auto importedNode = importer->ImportNode(srcPara, true);
dstDoc->get_FirstSection()->get_Body()->AppendChild(importedNode);
}
dstDoc->Save(outputDataDir + u"WorkingWithImportFormatOptions.IgnoreTextBoxes.docx");
auto srcDoc = System::MakeObject<Document>(inputDataDir + u"source.docx");
auto dstDoc = System::MakeObject<Document>(inputDataDir + u"destination.docx");
auto options = System::MakeObject<ImportFormatOptions>();
// Keep source list formatting when importing numbered paragraphs.
options->set_KeepSourceNumbering(true);
auto importer = System::MakeObject<NodeImporter>(srcDoc, dstDoc, ImportFormatMode::KeepSourceFormatting, options);
auto srcParas = srcDoc->get_FirstSection()->get_Body()->get_Paragraphs();
for (const auto& srcPara : System::IterateOver<Paragraph>(srcParas))
{
auto importedNode = importer->ImportNode(srcPara, false);
dstDoc->get_FirstSection()->get_Body()->AppendChild(importedNode);
}
dstDoc->Save(outputDataDir + u"WorkingWithImportFormatOptions.KeepSourceNumbering.docx");
auto srcDoc = System::MakeObject<Document>(inputDataDir + u"source.docx");
auto dstDoc = System::MakeObject<Document>(inputDataDir + u"destination.docx");
auto builder = System::MakeObject<DocumentBuilder>(dstDoc);
builder->MoveToDocumentEnd();
builder->InsertBreak(BreakType::PageBreak);
auto options = System::MakeObject<ImportFormatOptions>();
options->set_SmartStyleBehavior(true);
builder->InsertDocument(srcDoc, ImportFormatMode::UseDestinationStyles, options);
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Specify the "Heading 1" style for the paragraph.
builder->get_ParagraphFormat()->set_StyleName(u"Heading 1");
builder->Writeln(u"Heading 1");
// Reset styles from the previous paragraph to not combine styles between paragraphs.
builder->get_ParagraphFormat()->set_StyleName(u"Normal");
// Insert horizontal rule.
builder->InsertHorizontalRule();
// Specify the ordered list.
builder->InsertParagraph();
builder->get_ListFormat()->ApplyNumberDefault();
// Specify the Italic emphasis for the text.
builder->get_Font()->set_Italic(true);
builder->Writeln(u"Italic Text");
builder->get_Font()->set_Italic(false);
// Specify the Bold emphasis for the text.
builder->get_Font()->set_Bold(true);
builder->Writeln(u"Bold Text");
builder->get_Font()->set_Bold(false);
// Specify the StrikeThrough emphasis for the text.
builder->get_Font()->set_StrikeThrough(true);
builder->Writeln(u"StrikeThrough Text");
builder->get_Font()->set_StrikeThrough(false);
// Stop paragraphs numbering.
builder->get_ListFormat()->RemoveNumbers();
// Specify the "Quote" style for the paragraph.
builder->get_ParagraphFormat()->set_StyleName(u"Quote");
builder->Writeln(u"A Quote block");
// Specify nesting Quote.
auto nestedQuote = doc->get_Styles()->Add(StyleType::Paragraph, u"Quote1");
nestedQuote->set_BaseStyleName(u"Quote");
builder->get_ParagraphFormat()->set_StyleName(u"Quote1");
builder->Writeln(u"A nested Quote block");
// Reset paragraph style to Normal to stop Quote blocks.
builder->get_ParagraphFormat()->set_StyleName(u"Normal");
// Specify a Hyperlink for the desired text.
builder->get_Font()->set_Bold(true);
// Note, the text of hyperlink can be emphasized.
builder->InsertHyperlink(u"Aspose", u"https://www.aspose.com", false);
builder->get_Font()->set_Bold(false);
// Insert a simple table.
builder->StartTable();
builder->InsertCell();
builder->Write(u"Cell1");
builder->InsertCell();
builder->Write(u"Cell2");
builder->EndTable();
// Save your document as a Markdown file.
doc->Save(outputDataDir + u"CreateMarkdownDocument.md");
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"We support blockquotes in Markdown:");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Quote"));
builder->Writeln(u"Lorem");
builder->Writeln(u"ipsum");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Normal"));
builder->Writeln(u"The quotes can be of any level and can be nested:");
System::SharedPtr<Style> quoteLevel3 = doc->get_Styles()->Add(Aspose::Words::StyleType::Paragraph, u"Quote2");
builder->get_ParagraphFormat()->set_Style(quoteLevel3);
builder->Writeln(u"Quote level 3");
System::SharedPtr<Style> quoteLevel4 = doc->get_Styles()->Add(Aspose::Words::StyleType::Paragraph, u"Quote3");
builder->get_ParagraphFormat()->set_Style(quoteLevel4);
builder->Writeln(u"Nested quote level 4");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Quote"));
builder->Writeln();
builder->Writeln(u"Back to first level");
System::SharedPtr<Style> quoteLevel1WithHeading = doc->get_Styles()->Add(Aspose::Words::StyleType::Paragraph, u"Quote Heading 3");
builder->get_ParagraphFormat()->set_Style(quoteLevel1WithHeading);
builder->Write(u"Headings are allowed inside Quotes");
System::String outputPath = outputDataDir + u"WorkingWithMarkdownFeatures.MarkdownDocumentWithBlockQuotes.md";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Markdown treats asterisks (*) and underscores (_) as indicators of emphasis.");
builder->Write(u"You can write ");
builder->get_Font()->set_Bold(true);
builder->Write(u"bold");
builder->get_Font()->set_Bold(false);
builder->Write(u" or ");
builder->get_Font()->set_Italic(true);
builder->Write(u"italic");
builder->get_Font()->set_Italic(false);
builder->Writeln(u" text. ");
builder->Write(u"You can also write ");
builder->get_Font()->set_Bold(true);
builder->get_Font()->set_Italic(true);
builder->Write(u"BoldItalic");
builder->get_Font()->set_Bold(false);
builder->get_Font()->set_Italic(false);
builder->Write(u"text.");
System::String outputPath = outputDataDir + u"WorkingWithMarkdownFeatures.MarkdownDocumentWithEmphases.md";
builder->get_Document()->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// By default Heading styles in Word may have bold and italic formatting.
// If we do not want text to be emphasized, set these properties explicitly to false.
builder->get_Font()->set_Bold(false);
builder->get_Font()->set_Italic(false);
builder->Writeln(u"The following produces headings:");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 1"));
builder->Writeln(u"Heading1");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 2"));
builder->Writeln(u"Heading2");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 3"));
builder->Writeln(u"Heading3");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 4"));
builder->Writeln(u"Heading4");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 5"));
builder->Writeln(u"Heading5");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 6"));
builder->Writeln(u"Heading6");
// Note, emphases are also allowed inside Headings:
builder->get_Font()->set_Bold(true);
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 1"));
builder->Writeln(u"Bold Heading1");
System::String outputPath = outputDataDir + u"WorkingWithMarkdownFeatures.MarkdownDocumentWithHeadings.md";
doc->Save(outputPath);
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(System::MakeObject<Document>());
builder->Writeln(u"We support Horizontal rules (Thematic breaks) in Markdown:");
builder->InsertHorizontalRule();
System::String outputPath = outputDataDir + u"WorkingWithMarkdownFeatures.MarkdownDocumentWithHorizontalRule.md";
builder->get_Document()->Save(outputPath);
// This is Markdown document that was produced in example of UC3.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"QuotesExample.md");
// Let's remove Heading formatting from a Quote in the very last paragraph.
System::SharedPtr<Paragraph> paragraph = doc->get_FirstSection()->get_Body()->get_LastParagraph();
paragraph->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Quote"));
System::String outputPath = outputDataDir + u"WorkingWithMarkdownFeatures.ReadMarkdownDocument.md";
doc->Save(outputPath);
auto doc = System::MakeObject<Document>(inputDataDir + u"Input.docx");
auto warnings = System::MakeObject<WarningInfoCollection>();
doc->set_WarningCallback(warnings);
doc->Save(outputDataDir + u"UseWarningSourceMarkdown.md");
for (auto warningInfo : System::IterateOver(warnings))
{
if (warningInfo->get_Source() == WarningSource::Markdown)
{
std::cout << warningInfo->get_Description().ToUtf8String() << '\n';
}
}
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Input.docx");
// Set Measurement Units to Inches
doc->get_LayoutOptions()->get_RevisionOptions()->set_MeasurementUnit(MeasurementUnits::Inches);
// Show deletion revisions in balloon
doc->get_LayoutOptions()->get_RevisionOptions()->set_ShowInBalloons(Layout::ShowInBalloons::FormatAndDelete);
// Show Comments
doc->get_LayoutOptions()->set_ShowComments(true);
doc->Save(outputDataDir + u"Revisions.SetMeasurementUnit_out.pdf");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Input.docx");
//Renders revision bars on the right side of a page.
doc->get_LayoutOptions()->get_RevisionOptions()->set_RevisionBarsPosition(Drawing::HorizontalAlignment::Right);
doc->Save(outputDataDir + u"Revisions.SetRevisionBarsPosition_out.pdf");
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Revisions.docx");
// Get the RevisionOptions object that controls the appearance of revisions
auto revisionOptions = doc->get_LayoutOptions()->get_RevisionOptions();
// Show deletion revisions in balloon
revisionOptions->set_ShowInBalloons(Layout::ShowInBalloons::FormatAndDelete);
System::String outputPath = outputDataDir + u"Revisions.ShowRevisionsInBalloons_out.pdf";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
// Start tracking and make some revisions.
doc->StartTrackRevisions(u"Author");
doc->get_FirstSection()->get_Body()->AppendParagraph(u"Hello world!");
// Revisions will now show up as normal text in the output document.
doc->AcceptAllRevisions();
System::String outputPath = outputDataDir + u"WorkingWithRevisions.AcceptRevisions.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Test.docx");
doc->UpdateListLabels();
// Switch to the revised version of the document.
doc->set_RevisionsView(RevisionsView::Final);
for (System::SharedPtr<Revision> revision : System::IterateOver(doc->get_Revisions()))
{
if (revision->get_ParentNode()->get_NodeType() == NodeType::Paragraph)
{
System::SharedPtr<Paragraph> paragraph = System::DynamicCast<Paragraph>(revision->get_ParentNode());
if (paragraph->get_IsListItem())
{
// Print revised version of LabelString and ListLevel.
System::Console::WriteLine(paragraph->get_ListLabel()->get_LabelString());
System::Console::WriteLine(paragraph->get_ListFormat()->get_ListLevel());
}
}
}
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFormatDescription.docx");
for (System::SharedPtr<Revision> revision : System::IterateOver(doc->get_Revisions()))
{
System::String groupText = revision->get_Group() != nullptr ? System::String(u"Revision group text: ") + revision->get_Group()->get_Text() : u"Revision has no group";
std::cout << "Type: " << System::ObjectExt::ToString(revision->get_RevisionType()).ToUtf8String() << std::endl;
std::cout << "Author: " << revision->get_Author().ToUtf8String() << std::endl;
std::cout << "Date: " << revision->get_DateTime().ToString().ToUtf8String() << std::endl;
std::cout << "Revision text: " << revision->get_ParentNode()->ToString(Aspose::Words::SaveFormat::Text).ToUtf8String() << std::endl;
std::cout << groupText.ToUtf8String() << std::endl;
}
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Revisions.docx");
for (System::SharedPtr<RevisionGroup> group : System::IterateOver(doc->get_Revisions()->get_Groups()))
{
std::cout << group->get_Author().ToUtf8String() << ", :" << System::ObjectExt::Box<RevisionType>(group->get_RevisionType())->ToString().ToUtf8String() << std::endl;
std::cout << group->get_Text().ToUtf8String() << std::endl;
}
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Revisions.docx");
System::SharedPtr<ParagraphCollection> paragraphs = doc->get_FirstSection()->get_Body()->get_Paragraphs();
for (int32_t i = 0; i < paragraphs->get_Count(); i++)
{
if (paragraphs->idx_get(i)->get_IsMoveFromRevision())
{
std::cout << "The paragraph " << i << " has been moved (deleted)." << std::endl;
}
if (paragraphs->idx_get(i)->get_IsMoveToRevision())
{
std::cout << "The paragraph " << i << " has been moved (inserted)." << std::endl;
}
}
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Revisions.docx");
//Do not render the comments in PDF
doc->get_LayoutOptions()->set_ShowComments(false);
System::String outputPath = outputDataDir + u"WorkingWithRevisions.SetShowCommentsinPDF.pdf";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Revisions.docx");
// Renders insert and delete revisions inline, format revisions in balloons.
doc->get_LayoutOptions()->get_RevisionOptions()->set_ShowInBalloons(Aspose::Words::Layout::ShowInBalloons::Format);
// Renders insert revisions inline, delete and format revisions in balloons.
//doc.LayoutOptions.RevisionOptions.ShowInBalloons = ShowInBalloons.FormatAndDelete;
System::String outputPath = outputDataDir + u"Revisions.ShowRevisionsInBalloons_out.pdf";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<RtfSaveOptions> options = System::MakeObject<RtfSaveOptions>();
options->set_SaveImagesAsWmf(true);
doc->Save(outputDataDir + u"WorkingWithRtfSaveOptions.SavingImagesAsWmf.rtf", options);
//Load the Word document
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
//Open Office uses centimeters when specifying lengths, widths and other measurable formatting
//and content properties in documents whereas MS Office uses inches.
System::SharedPtr<OdtSaveOptions> saveOptions = System::MakeObject<OdtSaveOptions>();
saveOptions->set_MeasureUnit(OdtSaveMeasureUnit::Inches);
System::String outputPath = outputDataDir + u"WorkingWithSaveOptions.SetMeasureUnitForODT.docx";
//Save the document into ODT
doc->Save(outputPath, saveOptions);
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
System::SharedPtr<OoxmlSaveOptions> options = System::MakeObject<OoxmlSaveOptions>();
options->set_UpdateLastSavedTimeProperty(true);
System::String outputPath = outputDataDir + u"WorkingWithSaveOptions.UpdateLastSavedTimeProperty.docx";
// Save the document to disk.
doc->Save(outputPath, options);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<TaskPane> taskPane = System::MakeObject<TaskPane>();
doc->get_WebExtensionTaskPanes()->Add(taskPane);
taskPane->set_DockState(TaskPaneDockState::Right);
taskPane->set_IsVisible(true);
taskPane->set_Width(300);
taskPane->get_WebExtension()->get_Reference()->set_Id(u"wa102923726");
taskPane->get_WebExtension()->get_Reference()->set_Version(u"1.0.0.0");
taskPane->get_WebExtension()->get_Reference()->set_StoreType(WebExtensionStoreType::OMEX);
taskPane->get_WebExtension()->get_Reference()->set_Store(u"th-TH");
doc->Save(outputDataDir + u"WorkingWithWebExtension.UsingWebExtensionTaskPanes.docx", SaveFormat::Docx);
auto doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
auto options = System::MakeObject<CleanupOptions>();
options->set_DuplicateStyle(true);
// Cleans duplicate styles from the document.
doc->Cleanup(options);
auto outputPath = outputDataDir + u"CleanupDuplicateStyle.docx";
doc->Save(outputPath);
auto doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
auto 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);
auto outputPath = outputDataDir + u"CleanupUnusedStylesandLists.docx";
doc->Save(outputPath);
auto doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
auto options = System::MakeObject<ImageWatermarkOptions>();
options->set_Scale(5);
options->set_IsWashout(false);
doc->get_Watermark()->SetImage(System::Drawing::Image::FromFile(inputDataDir + u"Watermark.png"), options);
auto outputPath = outputDataDir + u"AddImageWatermark.docx";
doc->Save(outputPath);
auto doc = System::MakeObject<Document>(inputDataDir + u"Document.doc");
auto options = System::MakeObject<TextWatermarkOptions>();
options->set_FontFamily(u"Arial");
options->set_FontSize(36);
options->set_Color(System::Drawing::Color::get_Black());
options->set_Layout(WatermarkLayout::Horizontal);
options->set_IsSemitrasparent(false);
doc->get_Watermark()->SetText(u"Test", options);
auto outputPath = outputDataDir + u"AddTextWatermark.docx";
doc->Save(outputPath);
auto doc = System::MakeObject<Document>(inputDataDir + u"TextWatermark.docx");
if (doc->get_Watermark()->get_Type() == WatermarkType::Text)
{
doc->get_Watermark()->Remove();
}
auto outputPath = outputDataDir + u"RemoveWatermark.docx";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
// Initialize document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Specify font formatting before adding text.
System::SharedPtr<Font> font = builder->get_Font();
font->set_Size(16);
font->set_Bold(true);
font->set_Color(System::Drawing::Color::get_Blue());
font->set_Name(u"Arial");
font->set_Underline(Underline::Dash);
builder->Write(u"Sample text.");
System::String outputPath = outputDataDir + u"WriteAndFont.doc";
doc->Save(outputPath);
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
// We will test this functionality creating a document with two fields with date formatting
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert content with German locale.
builder->get_Font()->set_LocaleId(1031);
builder->InsertField(u"MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
builder->Write(u" - ");
builder->InsertField(u"MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");
// Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from.
// Set the culture used during field update to the culture used by the field.
doc->get_FieldOptions()->set_FieldUpdateCultureSource(FieldUpdateCultureSource::FieldCode);
doc->get_MailMerge()->Execute(System::MakeArray<System::String>({u"Date2"}), System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::DateTime>(System::DateTime(2011, 1, 1))}));
System::String outputPath = outputDataDir + u"ChangeFieldUpdateCultureSource.doc";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Insert content with German locale.
builder->get_Font()->set_LocaleId(1031);
builder->InsertField(u"MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
builder->Write(u" - ");
builder->InsertField(u"MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");
typedef System::SharedPtr<System::Object> TObjectPtr;
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
// Create a blank document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> b = System::MakeObject<DocumentBuilder>(doc);
b->InsertField(u"MERGEFIELD Date");
// Store the current culture so it can be set back once mail merge is complete.
System::SharedPtr<System::Globalization::CultureInfo> currentCulture = System::Threading::Thread::get_CurrentThread()->get_CurrentCulture();
// Set to German language so dates and numbers are formatted using this culture during mail merge.
System::Threading::Thread::get_CurrentThread()->set_CurrentCulture(System::MakeObject<System::Globalization::CultureInfo>(u"de-DE"));
// Execute mail merge.
doc->get_MailMerge()->Execute(System::MakeArray<System::String>({u"Date"}), System::MakeArray<TObjectPtr>({System::ObjectExt::Box<System::DateTime>(System::DateTime::get_Now())}));
// Restore the original culture.
System::Threading::Thread::get_CurrentThread()->set_CurrentCulture(currentCulture);
System::String outputPath = outputDataDir + u"ChangeLocale.doc";
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Pass the appropriate parameters to convert PAGE fields encountered to static text only in the body of the first section.
ConvertFieldsToStaticText(doc->get_FirstSection()->get_Body(), FieldType::FieldPage);
System::String outputPath = outputDataDir + u"ConvertFieldsInBody.doc";
// Save the document with fields transformed to disk.
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Pass the appropriate parameters to convert all IF fields encountered in the document (including headers and footers) to static text.
ConvertFieldsToStaticText(doc, FieldType::FieldIf);
System::String outputPath = outputDataDir + u"ConvertFieldsInDocument.doc";
// Save the document with fields transformed to disk.
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Pass the appropriate parameters to convert all IF fields to static text that are encountered only in the last
// Paragraph of the document.
ConvertFieldsToStaticText(doc->get_FirstSection()->get_Body()->get_LastParagraph(), FieldType::FieldIf);
System::String outputPath = outputDataDir + u"ConvertFieldsInParagraph.doc";
// Save the document with fields transformed to disk.
doc->Save(outputPath);
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>();
System::SharedPtr<FieldIf> field = System::DynamicCast<FieldIf>(builder->InsertField(u"IF 1 = 1", nullptr));
FieldIfComparisonResult actualResult = field->EvaluateCondition();
std::cout << System::ObjectExt::Box<FieldIfComparisonResult>(actualResult)->ToString().ToUtf8String() << std::endl;
void ConvertFieldsToStaticText(System::SharedPtr<CompositeNode> compositeNode, FieldType targetFieldType)
{
for (System::SharedPtr<Field> field : System::IterateOver(compositeNode->get_Range()->get_Fields()))
{
if (field->get_Type() == targetFieldType)
{
field->Unlink();
}
}
}
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"FieldUpdateCultureProvider.docx");
doc->get_FieldOptions()->set_FieldUpdateCultureSource(FieldUpdateCultureSource::FieldCode);
doc->get_FieldOptions()->set_FieldUpdateCultureProvider(System::MakeObject<FieldUpdateCultureProvider>());
System::String outputPath = outputDataDir + u"FieldUpdateCulture.pdf";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>();
System::SharedPtr<Document> document = builder->get_Document();
System::SharedPtr<Field> field = builder->InsertField(u"=-1234567.89 \\# \"### ### ###.000\"", nullptr);
document->get_FieldOptions()->set_ResultFormatter(System::MakeObject<FieldResultFormatter>(u"[{0:N2}]", nullptr));
field->Update();
System::String outputPath = outputDataDir + u"FormatFieldResult.docx";
builder->get_Document()->Save(outputPath);
const System::String inputDataDir = GetInputDataDir_WorkingWithFields();
auto doc = System::MakeObject<Aspose::Words::Document>(inputDataDir + u"Document.doc");
doc->get_Range()->get_FormFields()->idx_get(0)->get_Font()->set_Size(20);
doc->get_Range()->get_FormFields()->idx_get(0)->get_Font()->set_Color(System::Drawing::Color::get_Red());
const System::String outDataDir = GetOutputDataDir_WorkingWithFields();
doc->Save(outDataDir + u"FormFieldsFontFormatting.doc");
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"FormFields.doc");
System::SharedPtr<FormFieldCollection> documentFormFields = doc->get_Range()->get_FormFields();
System::SharedPtr<FormField> formField1 = documentFormFields->idx_get(3);
System::SharedPtr<FormField> formField2 = documentFormFields->idx_get(u"Text2");
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"FormFields.doc");
System::SharedPtr<FormFieldCollection> formFields = doc->get_Range()->get_FormFields();
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"FormFields.doc");
System::SharedPtr<FormField> formField = doc->get_Range()->get_FormFields()->idx_get(3);
if (formField->get_Type() == FieldType::FieldFormTextInput)
{
formField->set_Result(System::String(u"My name is ") + formField->get_Name());
}
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Shows how to delete all merge fields from a document without executing mail merge.
doc->get_MailMerge()->DeleteFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Shows how to get names of all merge fields in a document.
System::ArrayPtr<System::String> fieldNames = doc->get_MailMerge()->GetFieldNames();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Shows how to add a mapping when a merge field in a document and a data field in a data source have different names.
doc->get_MailMerge()->get_MappedDataFields()->Add(u"MyFieldName_InDocument", u"MyFieldName_InDataSource");
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"in.doc");
// Get paragraph you want to append this Advance field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an Advance field like this:
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
// Create instance of FieldAdvance class and lets build the above field code
System::SharedPtr<FieldAdvance> field = System::DynamicCast<FieldAdvance>(para->AppendField(FieldType::FieldAdvance, false));
// { ADVANCE \\d 10 " }
field->set_DownOffset(u"10");
// { ADVANCE \\d 10 \\l 10 }
field->set_LeftOffset(u"10");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 }
field->set_RightOffset(u"-3.3");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 }
field->set_UpOffset(u"0");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 }
field->set_HorizontalPosition(u"100");
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
field->set_VerticalPosition(u"100");
// Finally update this Advance field
field->Update();
System::String outputPath = outputDataDir + u"InsertAdvanceFieldWithoutDocumentBuilder.doc";
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"in.doc");
// Get paragraph you want to append this Ask field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an Ask field like this:
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
// Create instance of FieldAsk class and lets build the above field code
System::SharedPtr<FieldAsk> field = System::DynamicCast<FieldAsk>(para->AppendField(FieldType::FieldAsk, false));
// { ASK \"Test 1\" " }
field->set_BookmarkName(u"Test 1");
// { ASK \"Test 1\" Test2 }
field->set_PromptText(u"Test2");
// { ASK \"Test 1\" Test2 \\d Test3 }
field->set_DefaultResponse(u"Test3");
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
field->set_PromptOnceOnMailMerge(true);
// Finally update this Ask field
field->Update();
System::String outputPath = outputDataDir + u"InsertASKFieldWithoutDocumentBuilder.doc";
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"in.doc");
// Get paragraph you want to append this AUTHOR field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an AUTHOR field like this:
// { AUTHOR Test1 }
// Create instance of FieldAuthor class and lets build the above field code
System::SharedPtr<FieldAuthor> field = System::DynamicCast<FieldAuthor>(para->AppendField(FieldType::FieldAuthor, false));
// { AUTHOR Test1 }
field->set_AuthorName(u"Test1");
// Finally update this AUTHOR field
field->Update();
System::String outputPath = outputDataDir + u"InsertAuthorField.doc";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD MyFieldName \\* MERGEFORMAT");
System::String outputPath = outputDataDir + u"InsertField.docx";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<FieldUnknown> field = System::DynamicCast<FieldUnknown>(builder->InsertField(FieldType::FieldNone, false));
System::String outputPath = outputDataDir + u"InsertFieldNone.docx";
doc->Save(outputPath);
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD MyFieldName \\* MERGEFORMAT");
System::String outputPath = outputDataDir + u"InsertField.docx";
doc->Save(outputPath);
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::ArrayPtr<System::String> items = System::MakeArray<System::String>({u"One", u"Two", u"Three"});
builder->InsertComboBox(u"DropDown", items, 0);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"in.doc");
// Get paragraph you want to append this INCLUDETEXT field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
// Create instance of FieldAsk class and lets build the above field code
System::SharedPtr<FieldIncludeText> fieldIncludeText = System::DynamicCast<FieldIncludeText>(para->AppendField(FieldType::FieldIncludeText, false));
fieldIncludeText->set_BookmarkName(u"bookmark");
fieldIncludeText->set_SourceFullName(inputDataDir + u"IncludeText.docx");
doc->get_FirstSection()->get_Body()->AppendChild(para);
// Finally update this IncludeText field
fieldIncludeText->Update();
System::String outputPath = outputDataDir + u"InsertIncludeTextFieldWithoutDocumentBuilder.doc";
doc->Save(outputPath);
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithFields();
System::String outputDataDir = GetOutputDataDir_WorkingWithFields();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"in.doc");
// Get paragraph you want to append this INCLUDETEXT field to
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChildNodes(NodeType::Paragraph, true)->idx_get(1));
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
// Create instance of FieldAsk class and lets build the above field code
System::SharedPtr<FieldIncludeText> fieldIncludeText = System::DynamicCast<FieldIncludeText>(para->AppendField(FieldType::FieldIncludeText, false));
fieldIncludeText->set_BookmarkName(u"bookmark");
fieldIncludeText->set_SourceFullName(inputDataDir + u"IncludeText.docx");
doc->get_FirstSection()->get_Body()->AppendChild(para);
// Finally update this IncludeText field
fieldIncludeText->Update();
System::String outputPath = outputDataDir + u"InsertIncludeTextFieldWithoutDocumentBuilder.doc";
doc->Save(outputPath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment