Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
This Gist contains CSharp code snippets for examples of Aspose.Words for .NET.
using Aspose.Words;
using System;
namespace AsposeWordsDockerTest
{
class Program
{
static void Main(string[] args)
{
// Create document and save it in all available formats.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello from Aspose.Words!!!");
foreach (SaveFormat sf in Enum.GetValues(typeof(SaveFormat)))
{
if (sf != SaveFormat.Unknown)
{
try
{
doc.Save(string.Format("out{0}", FileFormatUtil.SaveFormatToExtension(sf)), sf);
Console.WriteLine("Saving {0}\t\t[OK]", sf);
}
catch
{
Console.WriteLine("Saving {0}\t\t[FAILED]", sf);
}
}
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "BubbleChart.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "template_cleanup.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
engine.Options = ReportBuildOptions.RemoveEmptyParagraphs;
engine.BuildReport(doc, Common.GetManagers(), "managers");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "BulletedList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetClients(), "clients");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "ChartWithFilteringGroupingOrdering.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class Client
{
public String Name { get; set; }
public String Country { get; set; }
public String LocalAddress { get; set; }
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
foreach (Manager manager in GetManagers())
{
foreach (Contract contract in manager.Contracts)
yield return contract.Client;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
foreach (Manager manager in GetManagers())
{
foreach (Contract contract in manager.Contracts)
yield return contract;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
IEnumerator<Manager> managers = GetManagers().GetEnumerator();
managers.MoveNext();
return managers.Current;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Manager manager = new Manager { Name = "John Smith", Age = 36, Photo = Photo() };
manager.Contracts = new Contract[]
{
new Contract { Client = new Client { Name = "A Company", Country= "Australia", LocalAddress = "219-241 Cleveland St STRAWBERRY HILLS NSW 1427" }, Manager = manager, Price = 1200000, Date = new DateTime(2015, 1, 1) },
new Contract { Client = new Client { Name = "B Ltd.", Country= "Brazil", LocalAddress = "Avenida João Jorge, 112, ap. 31 Vila Industrial Campinas - SP 13035-680"}, Manager = manager, Price = 750000, Date = new DateTime(2015, 4, 1) },
new Contract { Client = new Client { Name = "C & D", Country= "Canada", LocalAddress = "101-3485 RUE DE LA MONTAGNE MONTRÉAL (QUÉBEC) H3G 2A6" }, Manager = manager, Price = 350000, Date = new DateTime(2015, 7, 1) }
};
yield return manager;
manager = new Manager { Name = "Tony Anderson", Age = 37, Photo = Photo() };
manager.Contracts = new Contract[]
{
new Contract { Client = new Client { Name = "E Corp.", LocalAddress = "445 Mount Eden Road Mount Eden Auckland 1024" }, Manager = manager, Price = 650000, Date = new DateTime(2015, 2, 1) },
new Contract { Client = new Client { Name = "F & Partners", LocalAddress = "20 Greens Road Tuahiwi Kaiapoi 7691 " }, Manager = manager, Price = 550000, Date = new DateTime(2015, 8, 1) },
};
yield return manager;
manager = new Manager { Name = "July James", Age = 38, Photo = Photo() };
manager.Contracts = new Contract[]
{
new Contract { Client = new Client { Name = "G & Co.", Country= "Greece", LocalAddress = "Karkisias 6 GR-111 42 ATHINA GRÉCE" }, Manager = manager, Price = 350000, Date = new DateTime(2015, 2, 1) },
new Contract { Client = new Client { Name = "H Group", Country= "Hungary", LocalAddress = "Budapest Fiktív utca 82., IV. em./28.2806" }, Manager = manager, Price = 250000, Date = new DateTime(2015, 5, 1) },
new Contract { Client = new Client { Name = "I & Sons", LocalAddress ="43 Vogel Street Roslyn Palmerston North 4414" }, Manager = manager, Price = 100000, Date = new DateTime(2015, 7, 1) },
new Contract { Client = new Client { Name = "J Ent." , Country= "Japan", LocalAddress = "Hakusan 4-Chōme 3-2 Bunkyō-ku, TŌKYŌ 112-0001 Japan"}, Manager = manager, Price = 100000, Date = new DateTime(2015, 8, 1) }
};
yield return manager;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
// Load the photo and read all bytes.
byte[] imgdata = System.IO.File.ReadAllBytes(dataDir + "photo.png");
return imgdata;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "CommonList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetManagers(), "managers");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "CommonMasterDetail.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetManagers(), "managers");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "ConditionalBlock.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetClients(), "clients");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class Contract
{
public Manager Manager { get; set; }
public Client Client { get; set; }
public float Price { get; set; }
public DateTime Date { get; set; }
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "HelloWorld.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create an instance of sender class to set it's properties.
Sender sender = new Sender { Name = "LINQ Reporting Engine", Message = "Hello World" };
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, sender, "sender");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "InParagraphList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetClients(), "clients");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "InTableAlternateContent.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "InTableList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetManagers(), "managers");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "InTableMasterDetail.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetManagers(), "managers");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "InTableWithFilteringGroupingSorting.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class Manager
{
public String Name { get; set; }
public int Age { get; set; }
public byte[] Photo { get; set; }
public IEnumerable<Contract> Contracts { get; set; }
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "MulticoloredNumberedList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetClients(), "clients");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "NumberedList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetClients(), "clients");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "PieChart.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetManagers(), "managers");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "ScatterChart.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class Sender
{
public String Name { get; set; }
public String Message { get; set; }
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, new object());
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "SingleRow.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Load the photo and read all bytes.
byte[] imgdata = System.IO.File.ReadAllBytes(dataDir + "photo.png");
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetManager(), "manager");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Test File (doc).doc");
foreach (DigitalSignature signature in doc.DigitalSignatures)
{
Console.WriteLine("*** Signature Found ***");
Console.WriteLine("Is valid: " + signature.IsValid);
Console.WriteLine("Reason for signing: " + signature.Comments); // This property is available in MS Word documents only.
Console.WriteLine("Time of signing: " + signature.SignTime);
Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName.Name);
Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
Console.WriteLine();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string supportedDir = dataDir + "OutSupported";
string unknownDir = dataDir + "OutUnknown";
string encryptedDir = dataDir + "OutEncrypted";
string pre97Dir = dataDir + "OutPre97";
// Create the directories if they do not already exist
if (Directory.Exists(supportedDir) == false)
Directory.CreateDirectory(supportedDir);
if (Directory.Exists(unknownDir) == false)
Directory.CreateDirectory(unknownDir);
if (Directory.Exists(encryptedDir) == false)
Directory.CreateDirectory(encryptedDir);
if (Directory.Exists(pre97Dir) == false)
Directory.CreateDirectory(pre97Dir);
string[] fileList = Directory.GetFiles(dataDir);
// Loop through all found files.
foreach (string fileName in fileList)
{
// Extract and display the file name without the path.
string nameOnly = Path.GetFileName(fileName);
Console.Write(nameOnly);
// Check the file format and move the file to the appropriate folder.
FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);
// Display the document type.
switch (info.LoadFormat)
{
case LoadFormat.Doc:
Console.WriteLine("\tMicrosoft Word 97-2003 document.");
break;
case LoadFormat.Dot:
Console.WriteLine("\tMicrosoft Word 97-2003 template.");
break;
case LoadFormat.Docx:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document.");
break;
case LoadFormat.Docm:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
break;
case LoadFormat.Dotx:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template.");
break;
case LoadFormat.Dotm:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
break;
case LoadFormat.FlatOpc:
Console.WriteLine("\tFlat OPC document.");
break;
case LoadFormat.Rtf:
Console.WriteLine("\tRTF format.");
break;
case LoadFormat.WordML:
Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
break;
case LoadFormat.Html:
Console.WriteLine("\tHTML format.");
break;
case LoadFormat.Mhtml:
Console.WriteLine("\tMHTML (Web archive) format.");
break;
case LoadFormat.Odt:
Console.WriteLine("\tOpenDocument Text.");
break;
case LoadFormat.Ott:
Console.WriteLine("\tOpenDocument Text Template.");
break;
case LoadFormat.DocPreWord60:
Console.WriteLine("\tMS Word 6 or Word 95 format.");
break;
case LoadFormat.Unknown:
default:
Console.WriteLine("\tUnknown format.");
break;
}
// Now copy the document into the appropriate folder.
if (info.IsEncrypted)
{
Console.WriteLine("\tAn encrypted document.");
File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), true);
}
else
{
switch (info.LoadFormat)
{
case LoadFormat.DocPreWord60:
File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), true);
break;
case LoadFormat.Unknown:
File.Copy(fileName, Path.Combine(unknownDir, nameOnly), true);
break;
default:
File.Copy(fileName, Path.Combine(supportedDir, nameOnly), true);
break;
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Check the file format and move the file to the appropriate folder.
FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);
// Display the document type.
switch (info.LoadFormat)
{
case LoadFormat.Doc:
Console.WriteLine("\tMicrosoft Word 97-2003 document.");
break;
case LoadFormat.Dot:
Console.WriteLine("\tMicrosoft Word 97-2003 template.");
break;
case LoadFormat.Docx:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document.");
break;
case LoadFormat.Docm:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
break;
case LoadFormat.Dotx:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template.");
break;
case LoadFormat.Dotm:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
break;
case LoadFormat.FlatOpc:
Console.WriteLine("\tFlat OPC document.");
break;
case LoadFormat.Rtf:
Console.WriteLine("\tRTF format.");
break;
case LoadFormat.WordML:
Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
break;
case LoadFormat.Html:
Console.WriteLine("\tHTML format.");
break;
case LoadFormat.Mhtml:
Console.WriteLine("\tMHTML (Web archive) format.");
break;
case LoadFormat.Odt:
Console.WriteLine("\tOpenDocument Text.");
break;
case LoadFormat.Ott:
Console.WriteLine("\tOpenDocument Text Template.");
break;
case LoadFormat.DocPreWord60:
Console.WriteLine("\tMS Word 6 or Word 95 format.");
break;
case LoadFormat.Unknown:
default:
Console.WriteLine("\tUnknown format.");
break;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string[] fileList = Directory.GetFiles(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
// Create a new memory stream.
MemoryStream outStream = new MemoryStream();
// Save the document to stream.
doc.Save(outStream, SaveFormat.Docx);
// Convert the document to byte form.
byte[] 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.
MemoryStream inStream = new MemoryStream(docBytes);
// Load the stream into a new document object.
Document loadDoc = new Document(inStream);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// How the output document is saved.
HtmlSaveOptions saveOptions =
new HtmlSaveOptions();
// Specify the desired encoding.
saveOptions.Encoding = System.Text.Encoding.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.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;
// Specify that we want to export document properties.
saveOptions.ExportDocumentProperties = true;
// Specify that we want to save in EPUB format.
saveOptions.SaveFormat = SaveFormat.Epub;
// Export the document as an EPUB file.
doc.Save(dataDir + "Document.EpubConversion_out.epub", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void ConvertDocumentToEPUBUsingDefaultSaveOption()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Save the document in EPUB format.
doc.Save(dataDir + "Document.EpubConversionUsingDefaultSaveOption_out.epub");
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlSaveOptions options = new 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.ExportRoundtripInformation = true;
doc.Save(dataDir + "ExportRoundtripInformation_out.html", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Words.
Document doc = new Document(dataDir + "Test File (docx).docx");
// Save into a memory stream in MHTML format.
Stream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Mhtml);
// Rewind the stream to the beginning so Aspose.Email can read it.
stream.Position = 0;
// Create an Aspose.Network MIME email message from the stream.
MailMessage message = MailMessage.Load(stream, new MhtmlLoadOptions());
message.From = "your_from@email.com";
message.To = "your_to@email.com";
message.Subject = "Aspose.Words + Aspose.Email MHTML Test Message";
// Send the message using Aspose.Email
SmtpClient client = new SmtpClient();
client.Host = "your_smtp.com";
client.Send(message);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (docx).docx");
PclSaveOptions saveOptions = new PclSaveOptions();
saveOptions.SaveFormat = SaveFormat.Pcl;
saveOptions.RasterizeTransformedElements = false;
// Export the document as an PCL file.
doc.Save(dataDir + "Document.PclConversion_out.pcl", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Initialize a Document.
Document doc = new Document();
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello World!");
dataDir = dataDir + "CreateDocument_out.docx";
// Save the document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// The path to the document which is to be processed.
string filePath = dataDir + "Document.Signed.docx";
FileFormatInfo info = FileFormatUtil.DetectFileFormat(filePath);
if (info.HasDigitalSignature)
{
Console.WriteLine("Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.", Path.GetFileName(filePath));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");
// Load the certificate from disk.
// The other constructor overloads can be used to load certificates from different locations.
X509Certificate2 cert = new X509Certificate2(
dataDir + "signature.pfx", "signature");
// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails();
dataDir = dataDir + "Document.Signed_out.pdf";
// Save the document as PDF.
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
using System.Security.Cryptography.X509Certificates;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(
CertificateHolder.Create(dataDir + "CioSrv1.pfx", "cinD96..arellA"),"reason","location",DateTime.Now);
doc.Save(dataDir + @"DigitallySignedPdfUsingCertificateHolder.Signed_out.pdf", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
// Load the document from disk.
Document doc = new Document(dataDir + "Template.doc");
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.DisplayDocTitle = true;
dataDir = dataDir + "Template_out.pdf";
// Save the document in PDF format.
doc.Save(dataDir, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
// Load the document from disk.
Document doc = new Document(dataDir + "Template.doc");
dataDir = dataDir + "Template_out.pdf";
// Save the document in PDF format.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = "Document.doc";
Document doc = new Document(dataDir + fileName);
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.ExportFontResources = true;
saveOptions.ExportFontsAsBase64 = true;
dataDir = dataDir + "ExportFontsAsBase64_out.html";
doc.Save(dataDir, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = "Document.doc";
Document doc = new Document(dataDir + fileName);
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.CssStyleSheetType = CssStyleSheetType.External;
saveOptions.ExportFontResources = true;
saveOptions.ResourceFolder = dataDir + @"\Resources";
saveOptions.ResourceFolderAlias = "http://example.com/resources";
doc.Save(dataDir + "ExportResourcesUsingHtmlSaveOptions.html", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class ImageLoadingWithCredentialsHandler : IResourceLoadingCallback
{
public ImageLoadingWithCredentialsHandler()
{
mWebClient = new WebClient();
}
public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
{
if (args.ResourceType == ResourceType.Image)
{
Uri uri = new Uri(args.Uri);
if (uri.Host == "www.aspose.com")
mWebClient.Credentials = new NetworkCredential("User1", "akjdlsfkjs");
else
mWebClient.Credentials = new NetworkCredential("SomeOtherUserID", "wiurlnlvs");
// Download the bytes from the location referenced by the URI.
byte[] imageBytes = mWebClient.DownloadData(args.Uri);
args.SetData(imageBytes);
return ResourceLoadingAction.UserProvided;
}
else
{
return ResourceLoadingAction.Default;
}
}
private WebClient mWebClient;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Create Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Read the image from file, ensure it is disposed.
using (Image image = Image.FromFile(inputFileName))
{
// Find which dimension the frames in this image represent. For example
// The frames of a BMP or TIFF are "page dimension" whereas frames of a GIF image are "time dimension".
FrameDimension dimension = new FrameDimension(image.FrameDimensionsList[0]);
// Get the number of frames in the image.
int framesCount = image.GetFrameCount(dimension);
// Loop through all frames.
for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
{
// Insert a section break before each new page, in case of a multi-frame TIFF.
if (frameIdx != 0)
builder.InsertBreak(BreakType.SectionBreakNewPage);
// Select active frame.
image.SelectActiveFrame(dimension, frameIdx);
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
PageSetup ps = builder.PageSetup;
ps.PageWidth = ConvertUtil.PixelToPoint(image.Width, image.HorizontalResolution);
ps.PageHeight = ConvertUtil.PixelToPoint(image.Height, image.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.PageWidth,
ps.PageHeight,
WrapType.None);
}
}
// Save the document to PDF.
doc.Save(outputFileName);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
ConvertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg_out.pdf");
ConvertImageToPdf(dataDir + "Test.png", dataDir + "TestPng_out.pdf");
ConvertImageToPdf(dataDir + "Test.wmf", dataDir + "TestWmf_out.pdf");
ConvertImageToPdf(dataDir + "Test.tiff", dataDir + "TestTif_out.pdf");
ConvertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
LoadOptions options = new LoadOptions();
options.AnnotationsAtBlockLevel = true;
Document doc = new Document(dataDir + "AnnotationsAtBlockLevel.docx", options);
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag sdt = (StructuredDocumentTag)doc.GetChildNodes(NodeType.StructuredDocumentTag, true)[0];
BookmarkStart start = builder.StartBookmark("bm");
BookmarkEnd end = builder.EndBookmark("bm");
sdt.ParentNode.InsertBefore(start, sdt);
sdt.ParentNode.InsertAfter(end, sdt);
//Save the document into DOCX
doc.Save(dataDir + "AnnotationsAtBlockLevel_out.docx", SaveFormat.Docx);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
LoadOptions lo = new LoadOptions();
lo.ConvertShapeToOfficeMath = true;
// Specify load option to use previous default behaviour i.e. convert math shapes to office math ojects on loading stage.
Document doc = new Document(dataDir + @"OfficeMath.docx", lo);
//Save the document into DOCX
doc.Save(dataDir + "ConvertShapeToOfficeMath_out.docx", SaveFormat.Docx);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + @"encrypted.odt", new Aspose.Words.LoadOptions("password"));
doc.Save(dataDir + "out.odt", new OdtSaveOptions("newpassword"));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
LoadOptions lo = new LoadOptions();
//Update the fields with the dirty attribute
lo.UpdateDirtyFields = true;
//Load the Word document
Document doc = new Document(dataDir + @"input.docx", lo);
//Save the document into DOCX
doc.Save(dataDir + "output.docx", SaveFormat.Docx);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
FileFormatInfo info = FileFormatUtil.DetectFileFormat(dataDir + @"encrypted.odt");
Console.WriteLine(info.IsEncrypted);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void DeleteFromDatabase(string fileName, OleDbConnection mConnection)
{
// Create the SQL command.
string commandString = "DELETE * FROM Documents WHERE FileName='" + fileName + "'";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Delete the record.
command.ExecuteNonQuery();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string dbName = "";
// Open a database connection.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + RunExamples.GetDataDir_Database() + dbName;
OleDbConnection mConnection = new OleDbConnection(connString);
mConnection.Open();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Store the document to the database.
StoreToDatabase(doc, mConnection);
// Read the document from the database and store the file to disk.
Document dbDoc = ReadFromDatabase(fileName, mConnection);
// Save the retrieved document to disk.
string newFileName = Path.GetFileNameWithoutExtension(fileName) + " from DB" + Path.GetExtension(fileName);
dbDoc.Save(dataDir + newFileName);
// Delete the document from the database.
DeleteFromDatabase(fileName, mConnection);
// Close the connection to the database.
mConnection.Close();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static Document ReadFromDatabase(string fileName, OleDbConnection mConnection)
{
// Create the SQL command.
string commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Create the data adapter.
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
// Fill the results from the database into a DataTable.
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
// Check there was a matching record found from the database and throw an exception if no record was found.
if (dataTable.Rows.Count == 0)
throw new ArgumentException(string.Format("Could not find any record matching the document \"{0}\" in the database.", fileName));
// The document is stored in byte form in the FileContent column.
// Retrieve these bytes of the first matching record to a new buffer.
byte[] buffer = (byte[])dataTable.Rows[0]["FileContent"];
// Wrap the bytes from the buffer into a new MemoryStream object.
MemoryStream newStream = new MemoryStream(buffer);
// Read the document from the stream.
Document doc = new Document(newStream);
// Return the retrieved document.
return doc;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void StoreToDatabase(Document doc, OleDbConnection mConnection)
{
// Save the document to a MemoryStream object.
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Doc);
// Get the filename from the document.
string fileName = Path.GetFileName(doc.OriginalFileName);
// Create the SQL command.
string commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + fileName + "', @Doc)";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Add the @Doc parameter.
command.Parameters.AddWithValue("Doc", stream.ToArray());
// Write the document to the database.
command.ExecuteNonQuery();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
HtmlLoadOptions lo = new HtmlLoadOptions();
lo.PreferredControlType = HtmlControlType.StructuredDocumentTag;
//Load the HTML document
Document doc = new Document(dataDir + @"input.html", lo);
//Save the HTML document into DOCX
doc.Save(dataDir + "output.docx", SaveFormat.Docx);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
string fileName = "Document.doc";
// Load the document from the absolute path on disk.
Document doc = new Document(dataDir + fileName);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document as DOCX document.");
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
string fileName = "Document.doc";
// Load the document from the absolute path on disk.
Document doc = new Document(dataDir + fileName);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
string fileName = "Document.doc";
// Open the stream. Read only access is enough for Aspose.Words to load a document.
Stream stream = File.OpenRead(dataDir + fileName);
// Load the entire document into memory.
Document doc = new 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.
MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Rtf);
// Rewind the stream position back to zero so it is ready for the next reader.
dstStream.Position = 0;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
string fileName = "Document.doc";
// Open the stream. Read only access is enough for Aspose.Words to load a document.
Stream stream = File.OpenRead(dataDir + fileName);
// Load the entire document into memory.
Document doc = new Document(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// The encoding of the text file is automatically detected.
Document doc = new Document(dataDir + "LoadTxt.txt");
// Save as any Aspose.Words supported format, such as DOCX.
dataDir = dataDir + "LoadTxt_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Loads encrypted document.
Document doc = new Document(dataDir + "LoadEncrypted.docx", new LoadOptions("aspose"));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Document.doc");
dataDir = dataDir + "Document.ConvertToTxt_out.txt";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Here is an SVG image: ");
builder.InsertHtml(
@"<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> ");
HtmlSaveOptions options = new HtmlSaveOptions();
options.MetafileFormat = HtmlMetafileFormat.Svg;
dataDir = dataDir + "ExportSVGinHTML_out.html";
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.docx");
HtmlSaveOptions options = new HtmlSaveOptions();
options.MetafileFormat = HtmlMetafileFormat.EmfOrWmf;
dataDir = dataDir + "SaveHtmlWithMetafileFormat_out.html";
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.docx");
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.CssStyleSheetType = CssStyleSheetType.External;
saveOptions.CssClassNamePrefix = "pfx_";
dataDir = dataDir + "CssClassNamePrefix_out.html";
doc.Save(dataDir, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
var doc = new Aspose.Words.Document(dataDir + "CidUrls.docx");
Aspose.Words.Saving.HtmlSaveOptions saveOptions = new Aspose.Words.Saving.HtmlSaveOptions(SaveFormat.Mhtml);
saveOptions.PrettyFormat = true;
saveOptions.ExportCidUrlsForMhtmlResources = true;
saveOptions.SaveFormat = SaveFormat.Mhtml;
dataDir = dataDir + "SetExportCidUrlsForMhtmlResources_out.mhtml";
doc.Save(dataDir, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Test File (docx).docx");
Aspose.Words.Saving.HtmlSaveOptions saveOptions = new Aspose.Words.Saving.HtmlSaveOptions(SaveFormat.Html);
saveOptions.PrettyFormat = true;
saveOptions.ResolveFontNames = true;
dataDir = dataDir + "ResolveFontNames_out.html";
doc.Save(dataDir, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlFixedSaveOptions options = new HtmlFixedSaveOptions();
options.UseTargetMachineFonts = true;
dataDir = dataDir + "UseFontFromTargetMachine_out.html";
// Save the document to disk.
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlFixedSaveOptions options = new 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.SaveFontFaceCssSeparately = false;
dataDir = dataDir + "WriteAllCSSrulesinSingleFile_out.html";
// Save the document to disk.
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Document.doc");
dataDir = dataDir + "Report_out.doc";
// If this method overload is causing a compiler error then you are using the Client Profile DLL whereas
// The Aspose.Words .NET 2.0 DLL must be used instead.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = "TestFile RenderShape.docx";
Document doc = new Document(dataDir + fileName);
// This is the directory we want the exported images to be saved to.
string imagesDir = Path.Combine(dataDir, "Images");
// The folder specified needs to exist and should be empty.
if (Directory.Exists(imagesDir))
Directory.Delete(imagesDir, true);
Directory.CreateDirectory(imagesDir);
// Set an option to export form fields as plain text, not as HTML input elements.
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
options.ExportTextInputFormFieldAsText = true;
options.ImagesFolder = imagesDir;
dataDir = dataDir + "Document.SaveWithOptions_out.html";
doc.Save(dataDir, options);
Document doc = new Document(dataDir + "Document.doc");
DocSaveOptions saveOptions = new DocSaveOptions();
saveOptions.AlwaysCompressMetafiles = false;
doc.Save("SmallMetafilesUncompressed.doc", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
DocSaveOptions docSaveOptions = new DocSaveOptions();
docSaveOptions.Password = "password";
dataDir = dataDir + "Document.Password_out.doc";
doc.Save(dataDir, docSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions();
ooxmlSaveOptions.Password = "password";
dataDir = dataDir + "Document.Password_out.docx";
doc.Save(dataDir, ooxmlSaveOptions);
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.FlatOpc);
so.KeepLegacyControlChars = true;
dataDir = dataDir + "Document_out.docx";
// Save the document to disk.
doc.Save(dataDir, so);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
// Set Word2016 version for document
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2016);
//Set the Strict compliance level.
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions
{
Compliance = OoxmlCompliance.Iso29500_2008_Strict,
SaveFormat = SaveFormat.Docx
};
dataDir = dataDir + "Document.Iso29500_2008_Strict_out.docx";
doc.Save(dataDir, ooxmlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions();
ooxmlSaveOptions.UpdateLastSavedTimeProperty = true;
dataDir = dataDir + "UpdateLastSavedTimeProperty_out.docx";
// Save the document to disk.
doc.Save(dataDir, ooxmlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
RtfLoadOptions loadOptions = new RtfLoadOptions();
loadOptions.RecognizeUtf8Text = true;
Document doc = new Document(dataDir + "Utf8Text.rtf", loadOptions);
dataDir = dataDir + "RecognizeUtf8Text_out.rtf";
doc.Save(dataDir);
Document doc = new Document(dataDir + "Input.docx");
TxtSaveOptions saveOptions = new TxtSaveOptions();
saveOptions.AddBidiMarks = true;
dataDir = dataDir + "Document.AddBidiMarks_out.txt";
doc.Save(dataDir, saveOptions);
Document doc1 = new Document("input_document");
doc1.Save(dataDir + "output1.txt");
Document doc2 = new Document("input_document");
TxtSaveOptions options = new TxtSaveOptions();
doc2.Save(dataDir + "output2.txt", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
TxtLoadOptions loadOptions = new TxtLoadOptions();
loadOptions.DetectNumberingWithWhitespaces = false;
Document doc = new Document(dataDir + "LoadTxt.txt", loadOptions);
dataDir = dataDir + "DetectNumberingWithWhitespaces_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "TxtExportHeadersFootersMode.docx");
TxtSaveOptions options = new TxtSaveOptions();
options.SaveFormat = SaveFormat.Text;
// All headers and footers are placed at the very end of the output document.
options.ExportHeadersFootersMode = TxtExportHeadersFootersMode.AllAtEnd;
doc.Save(dataDir + "outputFileNameA.txt", options);
// Only primary headers and footers are exported at the beginning and end of each section.
options.ExportHeadersFootersMode = TxtExportHeadersFootersMode.PrimaryOnly;
doc.Save(dataDir + "outputFileNameB.txt", options);
// No headers and footers are exported.
options.ExportHeadersFootersMode = TxtExportHeadersFootersMode.None;
doc.Save(dataDir + "outputFileNameC.txt", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
TxtLoadOptions loadOptions = new TxtLoadOptions();
loadOptions.LeadingSpacesOptions = TxtLeadingSpacesOptions.Trim;
loadOptions.TrailingSpacesOptions = TxtTrailingSpacesOptions.Trim;
Document doc = new Document(dataDir + "LoadTxt.txt", loadOptions);
dataDir = dataDir + "HandleSpacesOptions_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
dataDir = dataDir + "Document.ConvertToTxt_out.txt";
doc.Save(dataDir);
Document doc = new Document("input_document");
TxtSaveOptions options = new TxtSaveOptions();
options.ListIndentation.Count = 3;
options.ListIndentation.Character = ' ';
doc.Save(dataDir + "output.txt", options);
Document doc = new Document("input_document");
TxtSaveOptions options = new TxtSaveOptions();
options.ListIndentation.Count = 1;
options.ListIndentation.Character = '\t';
doc.Save(dataDir + "output.txt", options);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Document.dot");
if (doc.VbaProject != null)
{
foreach (VbaModule module in doc.VbaProject.Modules)
{
Console.WriteLine(module.SourceCode);
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
string fileName = "TestFile.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// Create a data source which has some data missing.
// This will result in some regions that are merged and some that remain after executing mail merge.
DataSet data = GetDataSource();
// Make sure that we have not set the removal of any unused regions as we will handle them manually.
// We achieve this by removing the RemoveUnusedRegions flag from the cleanup options by using the AND and NOT bitwise operators.
doc.MailMerge.CleanupOptions = doc.MailMerge.CleanupOptions & ~MailMergeCleanupOptions.RemoveUnusedRegions;
// Execute mail merge. Some regions will be merged with data, others left unmerged.
doc.MailMerge.ExecuteWithRegions(data);
// The regions which contained data now would of been merged. Any regions which had no data and were
// Not merged will still remain in the document.
Document mergedDoc = doc.Clone(); // ExSkip
// Apply logic to each unused region left in the document using the logic set out in the handler.
// The handler class must implement the IFieldMergingCallback interface.
ExecuteCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler());
// Save the output document to disk.
doc.Save(dataDir + "TestFile.CustomLogicEmptyRegions1_out.doc");
// Reload the original merged document.
doc = mergedDoc.Clone();
// Apply different logic to unused regions this time.
ExecuteCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler_MergeTable());
doc.Save(dataDir + "TestFile.CustomLogicEmptyRegions2_out.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Only handle the ContactDetails region in our handler.
ArrayList regions = new ArrayList();
regions.Add("ContactDetails");
ExecuteCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler(), regions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
dataSet.Relations.Add(new DataRelation("OrderToItem", orderTable.Columns["Order_Id"], itemTable.Columns["Order_Id"]));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Returns a DataSet object containing a DataTable for the unmerged regions in the specified document.
/// If regionsList is null all regions found within the document are included. If an ArrayList instance is present
/// The only the regions specified in the list that are found in the document are added.
/// </summary>
private static DataSet CreateDataSourceFromDocumentRegions(Document doc, ArrayList regionsList)
{
const string tableStartMarker = "TableStart:";
DataSet dataSet = new DataSet();
string tableName = null;
foreach (string fieldName in doc.MailMerge.GetFieldNames())
{
if (fieldName.Contains(tableStartMarker))
{
tableName = fieldName.Substring(tableStartMarker.Length);
}
else if (tableName != null)
{
// Only add the table name as a new DataTable if it doesn't already exists in the DataSet.
if (dataSet.Tables[tableName] == null)
{
DataTable table = new DataTable(tableName);
table.Columns.Add(fieldName);
// We only need to add the first field for the handler to be called for the fields in the region.
if (regionsList == null || regionsList.Contains(tableName))
{
table.Rows.Add("FirstField");
}
dataSet.Tables.Add(table);
}
tableName = null;
}
}
return dataSet;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
dataSet.Relations.Add(new DataRelation("OrderToItem", orderTable.Columns["Order_Id"], itemTable.Columns["Order_Id"], false));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class EmptyRegionsHandler : IFieldMergingCallback
{
/// <summary>
/// Called for each field belonging to an unmerged region in the document.
/// </summary>
public void FieldMerging(FieldMergingArgs args)
{
// Change the text of each field of the ContactDetails region individually.
if (args.TableName == "ContactDetails")
{
// Set the text of the field based off the field name.
if (args.FieldName == "Name")
args.Text = "(No details found)";
else if (args.FieldName == "Number")
args.Text = "(N/A)";
}
// Remove the entire table of the Suppliers region. Also check if the previous paragraph
// Before the table is a heading paragraph and if so remove that too.
if (args.TableName == "Suppliers")
{
Table table = (Table)args.Field.Start.GetAncestor(NodeType.Table);
// Check if the table has been removed from the document already.
if (table.ParentNode != null)
{
// Try to find the paragraph which precedes the table before the table is removed from the document.
if (table.PreviousSibling != null && table.PreviousSibling.NodeType == NodeType.Paragraph)
{
Paragraph previousPara = (Paragraph)table.PreviousSibling;
if (IsHeadingParagraph(previousPara))
previousPara.Remove();
}
table.Remove();
}
}
}
/// <summary>
/// Returns true if the paragraph uses any Heading style e.g Heading 1 to Heading 9
/// </summary>
private bool IsHeadingParagraph(Paragraph para)
{
return (para.ParagraphFormat.StyleIdentifier >= StyleIdentifier.Heading1 && para.ParagraphFormat.StyleIdentifier <= StyleIdentifier.Heading9);
}
public void ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do Nothing
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Applies logic defined in the passed handler class to all unused regions in the document. This allows to manually control
/// How unused regions are handled in the document.
/// </summary>
/// <param name="doc">The document containing unused regions</param>
/// <param name="handler">The handler which implements the IFieldMergingCallback interface and defines the logic to be applied to each unmerged region.</param>
public static void ExecuteCustomLogicOnEmptyRegions(Document doc, IFieldMergingCallback handler)
{
ExecuteCustomLogicOnEmptyRegions(doc, handler, null); // Pass null to handle all regions found in the document.
}
/// <summary>
/// Applies logic defined in the passed handler class to specific unused regions in the document as defined in regionsList. This allows to manually control
/// How unused regions are handled in the document.
/// </summary>
/// <param name="doc">The document containing unused regions</param>
/// <param name="handler">The handler which implements the IFieldMergingCallback interface and defines the logic to be applied to each unmerged region.</param>
/// <param name="regionsList">A list of strings corresponding to the region names that are to be handled by the supplied handler class. Other regions encountered will not be handled and are removed automatically.</param>
public static void ExecuteCustomLogicOnEmptyRegions(Document doc, IFieldMergingCallback handler, ArrayList regionsList)
{
// Certain regions can be skipped from applying logic to by not adding the table name inside the CreateEmptyDataSource method.
// Enable this cleanup option so any regions which are not handled by the user's logic are removed automatically.
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions;
// Set the user's handler which is called for each unmerged region.
doc.MailMerge.FieldMergingCallback = handler;
// Execute mail merge using the dummy dataset. The dummy data source contains the table names of
// Each unmerged region in the document (excluding ones that the user may have specified to be skipped). This will allow the handler
// To be called for each field in the unmerged regions.
doc.MailMerge.ExecuteWithRegions(CreateDataSourceFromDocumentRegions(doc, regionsList));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Replace the unused region in the table with a "no records" message and merge all cells into one.
if (args.TableName == "Suppliers")
{
if ((string)args.FieldValue == "FirstField")
{
// We will use the first paragraph to display our message. Make it centered within the table. The other fields in other cells
// within the table will be merged and won't be displayed so we don't need to do anything else with them.
parentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Center;
args.Text = "No records to display";
}
// Merge the cells of the table together.
Cell cell = (Cell)parentParagraph.GetAncestor(NodeType.Cell);
if (cell != null)
{
if (cell.IsFirstCell)
cell.CellFormat.HorizontalMerge = CellMerge.First; // If this cell is the first cell in the table then the merge is started using "CellMerge.First".
else
cell.CellFormat.HorizontalMerge = CellMerge.Previous; // Otherwise the merge is continued using "CellMerge.Previous".
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Store the parent paragraph of the current field for easy access.
Paragraph parentParagraph = args.Field.Start.ParentParagraph;
// Define the logic to be used when the ContactDetails region is encountered.
// The region is removed and replaced with a single line of text stating that there are no records.
if (args.TableName == "ContactDetails")
{
// Called for the first field encountered in a region. This can be used to execute logic on the first field
// In the region without needing to hard code the field name. Often the base logic is applied to the first field and
// Different logic for other fields. The rest of the fields in the region will have a null FieldValue.
if ((string)args.FieldValue == "FirstField")
{
FindReplaceOptions options = new FindReplaceOptions();
// Remove the "Name:" tag from the start of the paragraph
parentParagraph.Range.Replace("Name:", string.Empty, options);
// Set the text of the first field to display a message stating that there are no records.
args.Text = "No records to display";
}
else
{
// We have already inserted our message in the paragraph belonging to the first field. The other paragraphs in the region
// will still remain so we want to remove these. A check is added to ensure that the paragraph has not already been removed.
// which may happen if more than one field is included in a paragraph.
if (parentParagraph.ParentNode != null)
parentParagraph.Remove();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Open an existing document.
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc");
// Trim trailing and leading whitespaces mail merge values
doc.MailMerge.TrimWhitespaces = false;
// Fill the fields in the document with user data.
doc.MailMerge.Execute(
new string[] { "FullName", "Company", "Address", "Address2", "City" },
new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
dataDir = dataDir + "MailMerge.ExecuteArray_out.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(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
string fileName = "MailMerge.ExecuteWithRegions.doc";
Document doc = new Document(dataDir + fileName);
int orderId = 10444;
// Perform several mail merge operations populating only part of the document each time.
// Use DataTable as a data source.
DataTable orderTable = GetTestOrder(orderId);
doc.MailMerge.ExecuteWithRegions(orderTable);
// Instead of using DataTable you can create a DataView for custom sort or filter and then mail merge.
DataView orderDetailsView = new DataView(GetTestOrderDetails(orderId));
orderDetailsView.Sort = "ExtendedPrice DESC";
doc.MailMerge.ExecuteWithRegions(orderDetailsView);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static DataTable GetTestOrder(int orderId)
{
DataTable table = ExecuteDataTable(string.Format(
"SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId));
table.TableName = "Orders";
return table;
}
private static DataTable GetTestOrderDetails(int orderId)
{
DataTable table = ExecuteDataTable(string.Format(
"SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId));
table.TableName = "OrderDetails";
return table;
}
/// <summary>
/// Utility function that creates a connection, command,
/// Executes the command and return the result in a DataTable.
/// </summary>
private static DataTable ExecuteDataTable(string commandText)
{
// Open the database connection.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
RunExamples.GetDataDir_Database() + "Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
// Create and execute a command.
OleDbCommand cmd = new OleDbCommand(commandText, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
// Close the database.
conn.Close();
return table;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public sealed class MailMergeSwitches : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (e.FieldName.StartsWith("HTML"))
{
if (e.Field.GetFieldCode().Contains("\\b"))
{
FieldMergeField field = e.Field;
DocumentBuilder builder = new DocumentBuilder(e.Document);
builder.MoveToMergeField(e.DocumentFieldName, true, false);
builder.Write(field.TextBefore);
builder.InsertHtml(e.FieldValue.ToString());
e.Text = "";
}
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string fileName = "TestFile.LINQ.doc";
// Open the template document.
Document doc = new Document(dataDir + fileName);
// Fill the document with data from our data sources.
// Using mail merge regions for populating the order items table is required
// Because it allows the region to be repeated in the document for each order item.
doc.MailMerge.ExecuteWithRegions(orderItemsDataSource);
// The standard mail merge without regions is used for the delivery address.
doc.MailMerge.Execute(deliveryDataSource);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
var orderItems =
from order in orderXml.Descendants("Item")
select new
{
PartNumber = (string)order.Attribute("PartNumber"),
ProductName = (string)order.Element("ProductName"),
Quantity = (string)order.Element("Quantity"),
USPrice = (string)order.Element("USPrice"),
Comment = (string)order.Element("Comment"),
ShipDate = (string)order.Element("ShipDate")
};
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
var deliveryAddress =
from delivery in orderXml.Elements("Address")
where ((string)delivery.Attribute("Type") == "Shipping")
select new
{
Name = (string)delivery.Element("Name"),
Country = (string)delivery.Element("Country"),
Zip = (string)delivery.Element("Zip"),
State = (string)delivery.Element("State"),
City = (string)delivery.Element("City"),
Street = (string)delivery.Element("Street")
};
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class MyMailMergeDataSource : IMailMergeDataSource
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public MyMailMergeDataSource(IEnumerable data)
{
mEnumerator = data.GetEnumerator();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public MyMailMergeDataSource(IEnumerable data, string tableName)
{
mEnumerator = data.GetEnumerator();
mTableName = tableName;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public bool GetValue(string fieldName, out object fieldValue)
{
// Use reflection to get the property by name from the current object.
object obj = mEnumerator.Current;
Type curentRecordType = obj.GetType();
PropertyInfo property = curentRecordType.GetProperty(fieldName);
if (property != null)
{
fieldValue = property.GetValue(obj, null);
return true;
}
// Return False to the Aspose.Words mail merge engine to indicate the field was not found.
fieldValue = null;
return false;