Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This Gist contains code snippets from examples of Aspose.Words for C++.
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
This Gist contains code snippets from examples of Aspose.Words for C++.
// The path to the documents directory.
System::String 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;