Skip to content

Instantly share code, notes, and snippets.

@aspose-words
Last active March 9, 2023 05:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save aspose-words/9a306a41bb6aea8adfcabf5a575c5718 to your computer and use it in GitHub Desktop.
Save aspose-words/9a306a41bb6aea8adfcabf5a575c5718 to your computer and use it in GitHub Desktop.
This Gist contains CSharp code snippets for examples of Aspose.Words for .NET.
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
Examples-CSharp
// 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(string.Format("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
// 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);
// 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);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Input.docx");
TxtSaveOptions saveOptions = new TxtSaveOptions();
saveOptions.AddBidiMarks = false;
dataDir = dataDir + "Document.AddBidiMarks_out.txt";
doc.Save(dataDir, saveOptions);
// 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);
// 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;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public bool MoveNext()
{
return mEnumerator.MoveNext();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public string TableName
{
get { return mTableName; }
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class HandleMergeFieldAlternatingRows : IFieldMergingCallback
{
/// <summary>
/// Called for every merge field encountered in the document.
/// We can either return some data to the mail merge engine or do something
/// Else with the document. In this case we modify cell formatting.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.Document);
// This way we catch the beginning of a new row.
if (e.FieldName.Equals("CompanyName"))
{
// Select the color depending on whether the row number is even or odd.
Color rowColor;
if (IsOdd(mRowIdx))
rowColor = Color.FromArgb(213, 227, 235);
else
rowColor = Color.FromArgb(242, 242, 242);
// There is no way to set cell properties for the whole row at the moment,
// So we have to iterate over all cells in the row.
for (int colIdx = 0; colIdx < 4; colIdx++)
{
mBuilder.MoveToCell(0, mRowIdx, colIdx, 0);
mBuilder.CellFormat.Shading.BackgroundPatternColor = rowColor;
}
mRowIdx++;
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
private DocumentBuilder mBuilder;
private int mRowIdx;
}
/// <summary>
/// Returns true if the value is odd; false if the value is even.
/// </summary>
private static bool IsOdd(int value)
{
// The code is a bit complex, but otherwise automatic conversion to VB does not work.
return ((value / 2) * 2).Equals(value);
}
/// <summary>
/// Create DataTable and fill it with data.
/// In real life this DataTable should be filled from a database.
/// </summary>
private static DataTable GetSuppliersDataTable()
{
DataTable dataTable = new DataTable("Suppliers");
dataTable.Columns.Add("CompanyName");
dataTable.Columns.Add("ContactName");
for (int i = 0; i < 10; i++)
{
DataRow datarow = dataTable.NewRow();
dataTable.Rows.Add(datarow);
datarow[0] = "Company " + i.ToString();
datarow[1] = "Contact " + i.ToString();
}
return dataTable;
}
// 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();
Document doc = new Document(dataDir + "MailMerge.AlternatingRows.doc");
// Add a handler for the MergeField event.
doc.MailMerge.FieldMergingCallback = new HandleMergeFieldAlternatingRows();
// Execute mail merge with regions.
DataTable dataTable = GetSuppliersDataTable();
doc.MailMerge.ExecuteWithRegions(dataTable);
dataDir = dataDir + "MailMerge.AlternatingRows_out.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
using Aspose.Words.MailMerging;
// 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 + "UnconditionalMergeFieldsAndRegions.docx");
//Merge fields and merge regions are merged regardless of the parent IF field's condition.
doc.MailMerge.UnconditionalMergeFieldsAndRegions = true;
// Fill the fields in the document with user data.
doc.MailMerge.Execute(
new string[] { "FullName" },
new object[] { "James Bond" });
dataDir = dataDir + "UnconditionalMergeFieldsAndRegions_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string fileName = "MailMerge.CleanupPunctuationMarks.docx";
// Open the document.
Document doc = new Document(dataDir + fileName);
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
doc.MailMerge.CleanupParagraphsWithPunctuationMarks = false;
doc.MailMerge.Execute(new string[] { "field1", "field2" }, new object[] { "", "" });
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class HandleMergeField : IFieldMergingCallback
{
/// <summary>
/// This handler is called for every mail merge field found in the document,
/// for every record found in the data source.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.Document);
// We decided that we want all boolean values to be output as check box form fields.
if (e.FieldValue is bool)
{
// Move the "cursor" to the current merge field.
mBuilder.MoveToMergeField(e.FieldName);
// It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
string checkBoxName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
// Insert a check box.
mBuilder.InsertCheckBox(checkBoxName, (bool)e.FieldValue, 0);
// Nothing else to do for this field.
return;
}
// We want to insert html during mail merge.
if (e.FieldName == "Body")
{
mBuilder.MoveToMergeField(e.FieldName);
mBuilder.InsertHtml((string)e.FieldValue);
}
// Another example, we want the Subject field to come out as text input form field.
if (e.FieldName == "Subject")
{
mBuilder.MoveToMergeField(e.FieldName);
string textInputName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string)e.FieldValue, 0);
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
private DocumentBuilder mBuilder;
}
// 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 = "Template.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Setup mail merge event handler to do the custom work.
doc.MailMerge.FieldMergingCallback = new HandleMergeField();
// Trim trailing and leading whitespaces mail merge values
doc.MailMerge.TrimWhitespaces = false;
// This is the data for mail merge.
String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
"Subject", "Body", "Urgent", "ForReview", "PleaseComment"};
Object[] fieldValues = new Object[] {"Josh", "Jenny", "123456789", "", "Hello",
"<b>HTML Body Test message 1</b>", true, false, true};
// Execute the mail merge.
doc.MailMerge.Execute(fieldNames, fieldValues);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
// Do nothing.
}
/// <summary>
/// This is called when mail merge engine encounters Image:XXX merge field in the document.
/// You have a chance to return an Image object, file name or a stream that contains the image.
/// </summary>
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
{
// The field value is a byte array, just cast it and create a stream on it.
MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
// Now the mail merge engine will retrieve the image from the stream.
e.ImageStream = imageStream;
}
}
// 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();
Document doc = new Document(dataDir + "MailMerge.MergeImage.doc");
// Set up the event handler for image fields.
doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
// Open a database connection.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + RunExamples.GetDataDir_Database()+"Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
// Open the data reader. It needs to be in the normal mode that reads all record at once.
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
IDataReader dataReader = cmd.ExecuteReader();
// Perform mail merge.
doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");
// Close the database.
conn.Close();
dataDir = dataDir + "MailMerge.MergeImage_out.doc";
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();
DataSet ds = new DataSet();
ds.ReadXml(dataDir + "Vendors.xml");
// Open a template document.
Document doc = new Document(dataDir + "VendorTemplate.doc");
doc.MailMerge.UseNonMergeFields = true;
// Execute mail merge to fill the template with data from XML using DataSet.
doc.MailMerge.ExecuteWithRegions(ds);
dataDir = dataDir + "MailMergeUsingMustacheSyntax_out.docx";
// 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
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Create the Dataset and read the XML.
DataSet pizzaDs = new DataSet();
// Note: The Datatable.TableNames and the DataSet.Relations are defined implicitly by .NET through ReadXml.
// To see examples of how to set up relations manually check the corresponding documentation of this sample
pizzaDs.ReadXml(dataDir + "CustomerData.xml");
string fileName = "Invoice Template.doc";
// Open the template document.
Document doc = new Document(dataDir + fileName);
// Trim trailing and leading whitespaces mail merge values
doc.MailMerge.TrimWhitespaces = false;
// Execute the nested mail merge with regions
doc.MailMerge.ExecuteWithRegions(pizzaDs);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output to file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public IMailMergeDataSource GetChildDataSource(string tableName)
{
switch (tableName)
{
// Get the child collection to merge it with the region provided with tableName variable.
case "Order":
return new OrderMailMergeDataSource(mCustomers[mRecordIndex].Orders);
default:
return null;
}
}
// 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 = "NestedMailMerge.CustomDataSource.doc";
// Create some data that we will use in the mail merge.
CustomerList customers = new CustomerList();
customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));
// Create some data for nesting in the mail merge.
customers[0].Orders.Add(new Order("Rugby World Cup Cap", 2));
customers[0].Orders.Add(new Order("Rugby World Cup Ball", 1));
customers[1].Orders.Add(new Order("Rugby World Cup Guide", 1));
// Open the template document.
Document doc = new Document(dataDir + fileName);
// To be able to mail merge from your own data source, it must be wrapped
// Into an object that implements the IMailMergeDataSource interface.
CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);
// Now you can pass your data source into Aspose.Words.
doc.MailMerge.ExecuteWithRegions(customersDataSource);
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
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Open the database connection.
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataDir + "Customers.mdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
// Get data from a database.
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable data = new DataTable();
da.Fill(data);
// Open the template document.
Document doc = new Document(dataDir + "TestFile.doc");
int counter = 1;
// Loop though all records in the data source.
foreach (DataRow row in data.Rows)
{
// Clone the template instead of loading it from disk (for speed).
Document dstDoc = (Document)doc.Clone(true);
// Execute mail merge.
dstDoc.MailMerge.Execute(row);
// Save the document.
dstDoc.Save(string.Format(dataDir + "TestFile_out{0}.doc", counter++));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Set the appropriate mail merge clean up options to remove any unused regions from the document.
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions;
// Doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields;
// Doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveStaticFields;
// Doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveEmptyParagraphs;
// Doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveUnusedFields;
// 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 Empty.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// Create a dummy data source containing no data.
DataSet data = new DataSet();
// Set the appropriate mail merge clean up options to remove any unused regions from the document.
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions;
// Doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields;
// Doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveStaticFields;
// Doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveEmptyParagraphs;
// Doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveUnusedFields;
// Execute mail merge which will have no effect as there is no data. However the regions found in the document will be removed
// Automatically as they are unused.
doc.MailMerge.ExecuteWithRegions(data);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output 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_MailMergeAndReporting();
Document doc = new Document(dataDir + "RemoveRowfromTable.docx");
doc.MailMerge.Execute(new string[] { "FullName", "Company", "Address", "Address2", "City" }, new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyTableRows | MailMergeCleanupOptions.RemoveContainingFields;
doc.MailMerge.MergeDuplicateRegions = true;
dataDir = dataDir + "MailMerge.ExecuteArray_out.doc";
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();
// Open an existing document.
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc");
doc.MailMerge.UseNonMergeFields = true;
// 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();
// Create the Dataset and read the XML.
DataSet customersDs = new DataSet();
customersDs.ReadXml(dataDir + "Customers.xml");
string fileName = "TestFile XML.doc";
// Open a template document.
Document doc = new Document(dataDir + fileName);
// Execute mail merge to fill the template with data from XML using DataTable.
doc.MailMerge.Execute(customersDs.Tables["Customer"]);
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-cloud/aspose-words-cloud-dotnet
var localName = "Sample.pdf";
var remoteName = "Sample.pdf";
var fullName = Path.Combine(this.dataFolder, remoteName);
var format = "doc";
var destFileName = Path.Combine(BaseTestOutPath, Path.GetFileNameWithoutExtension(remoteName) + "." + format);
this.StorageApi.PutCreate(fullName, null, null, File.ReadAllBytes(BaseTestContext.GetDataDir(BaseTestContext.CommonFolder) + localName));
var request = new GetDocumentWithFormatRequest(remoteName, format, this.dataFolder, outPath: destFileName);
this.WordsApi.GetDocumentWithFormat(request);
var result = this.StorageApi.GetIsExist(destFileName, null, null);
Assert.IsNotNull(result, "Cannot download document from storage");
Assert.IsTrue(result.FileExist.IsExist, "File doesn't exist on storage");
// 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_WorkingWithBookmarks();
Document doc = new Document(dataDir + "Bookmarks.doc");
// By index.
Bookmark bookmark1 = doc.Range.Bookmarks[0];
// By name.
Bookmark bookmark2 = doc.Range.Bookmarks["Bookmark2"];
// 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_WorkingWithBookmarks();
Document doc = new Document(dataDir + "Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];
// Get the name and text of the bookmark.
string name = bookmark.Name;
string text = bookmark.Text;
// Set the name and text of the bookmark.
bookmark.Name = "RenamedBookmark";
bookmark.Text = "This is a new bookmarked text.";
// 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_WorkingWithBookmarks();
// Create empty document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
// Insert a cell
builder.InsertCell();
// Start bookmark here after calling InsertCell
builder.StartBookmark("MyBookmark");
builder.Write("This is row 1 cell 1");
// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");
builder.EndRow();
// Insert a cell
builder.InsertCell();
builder.Writeln("This is row 2 cell 1");
// Insert a cell
builder.InsertCell();
builder.Writeln("This is row 2 cell 2");
builder.EndRow();
builder.EndTable();
// End of bookmark
builder.EndBookmark("MyBookmark");
dataDir = dataDir + "Bookmark.Table_out.doc";
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_WorkingWithBookmarks();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartBookmark("My Bookmark");
builder.Writeln("Text inside a bookmark.");
builder.StartBookmark("Nested Bookmark");
builder.Writeln("Text inside a NestedBookmark.");
builder.EndBookmark("Nested Bookmark");
builder.Writeln("Text after Nested Bookmark.");
builder.EndBookmark("My Bookmark");
PdfSaveOptions options = new PdfSaveOptions();
options.OutlineOptions.BookmarksOutlineLevels.Add("My Bookmark", 1);
options.OutlineOptions.BookmarksOutlineLevels.Add("Nested Bookmark", 2);
dataDir = dataDir + "Create.Bookmark_out.pdf";
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();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add chart with default data.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
chart.Title.Text = "Data Labels With Different Number Format";
// Delete default generated series.
chart.Series.Clear();
// Add new series
ChartSeries series0 = chart.Series.Add("AW Series 0", new string[] { "AW0", "AW1", "AW2" }, new double[] { 2.5, 1.5, 3.5 });
// Add DataLabel to the first point of the first series.
ChartDataLabel chartDataLabel0 = series0.DataLabels.Add(0);
chartDataLabel0.ShowValue = true;
// Set currency format code.
chartDataLabel0.NumberFormat.FormatCode = "\"$\"#,##0.00";
ChartDataLabel chartDataLabel1 = series0.DataLabels.Add(1);
chartDataLabel1.ShowValue = true;
// Set date format code.
chartDataLabel1.NumberFormat.FormatCode = "d/mm/yyyy";
ChartDataLabel chartDataLabel2 = series0.DataLabels.Add(2);
chartDataLabel2.ShowValue = true;
// Set percentage format code.
chartDataLabel2.NumberFormat.FormatCode = "0.00%";
// Or you can set format code to be linked to a source cell,
// in this case NumberFormat will be reset to general and inherited from a source cell.
chartDataLabel2.NumberFormat.IsLinkedToSource = true;
dataDir = dataDir + @"NumberFormat_DataLabel_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_WorkingWithCharts();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
// Determines whether the title shall be shown for this chart. Default is true.
chart.Title.Show = true;
// Setting chart Title.
chart.Title.Text = "Sample Line Chart Title";
// Determines whether other chart elements shall be allowed to overlap title.
chart.Title.Overlay = false;
// Please note if null or empty value is specified as title text, auto generated title will be shown.
// Determines how legend shall be shown for this chart.
chart.Legend.Position = LegendPosition.Left;
chart.Legend.Overlay = true;
dataDir = dataDir + @"SimpleLineChart_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Get chart series collection.
ChartSeriesCollection seriesColl = chart.Series;
// Check series count.
Console.WriteLine(seriesColl.Count);
// 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);
// Insert Column chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
// Use this overload to add series to any type of Bar, Column, Line and Surface charts.
chart.Series.Add("AW Series 1", new string[] { "AW Category 1", "AW Category 2" }, new double[] { 1, 2 });
dataDir = dataDir + @"TestInsertChartColumn_out.doc";
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);
// Add chart with default data. You can specify different chart types and sizes.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
// Chart property of Shape contains all chart related options.
Chart chart = shape.Chart;
// Get chart series collection.
ChartSeriesCollection seriesColl = chart.Series;
// Check series count.
Console.WriteLine(seriesColl.Count);
// Delete default generated series.
seriesColl.Clear();
// Create category names array, in this example we have two categories.
string[] categories = new string[] { "AW Category 1", "AW Category 2" };
// Adding new series. Please note, data arrays must not be empty and arrays must be the same size.
seriesColl.Add("AW Series 1", categories, new double[] { 1, 2 });
seriesColl.Add("AW Series 2", categories, new double[] { 3, 4 });
seriesColl.Add("AW Series 3", categories, new double[] { 5, 6 });
seriesColl.Add("AW Series 4", categories, new double[] { 7, 8 });
seriesColl.Add("AW Series 5", categories, new double[] { 9, 10 });
dataDir = dataDir + @"TestInsertSimpleChartColumn_out.doc";
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_WorkingWithCharts();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert Area chart.
Shape shape = builder.InsertChart(ChartType.Area, 432, 252);
Chart chart = shape.Chart;
// Use this overload to add series to any type of Area, Radar and Stock charts.
chart.Series.Add("AW Series 1", new DateTime[] {
new DateTime(2002, 05, 01),
new DateTime(2002, 06, 01),
new DateTime(2002, 07, 01),
new DateTime(2002, 08, 01),
new DateTime(2002, 09, 01)}, new double[] { 32, 32, 28, 12, 15 });
dataDir = dataDir + @"TestInsertAreaChart_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_WorkingWithCharts();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert Bubble chart.
Shape shape = builder.InsertChart(ChartType.Bubble, 432, 252);
Chart chart = shape.Chart;
// Use this overload to add series to any type of Bubble charts.
chart.Series.Add("AW Series 1", new double[] { 0.7, 1.8, 2.6 }, new double[] { 2.7, 3.2, 0.8 }, new double[] { 10, 4, 8 });
dataDir = dataDir + @"TestInsertBubbleChart_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_WorkingWithCharts();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert Scatter chart.
Shape shape = builder.InsertChart(ChartType.Scatter, 432, 252);
Chart chart = shape.Chart;
// Use this overload to add series to any type of Scatter charts.
chart.Series.Add("AW Series 1", new double[] { 0.7, 1.8, 2.6 }, new double[] { 2.7, 3.2, 0.8 });
dataDir = dataDir + "TestInsertScatterChart_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();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Area, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
// Fill data.
chart.Series.Add("AW Series 1",
new DateTime[] { new DateTime(2002, 01, 01), new DateTime(2002, 06, 01), new DateTime(2002, 07, 01), new DateTime(2002, 08, 01), new DateTime(2002, 09, 01) },
new double[] { 640, 320, 280, 120, 150 });
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;
// Change the X axis to be category instead of date, so all the points will be put with equal interval on the X axis.
xAxis.CategoryType = AxisCategoryType.Category;
// Define X axis properties.
xAxis.Crosses = AxisCrosses.Custom;
xAxis.CrossesAt = 3; // measured in display units of the Y axis (hundreds)
xAxis.ReverseOrder = true;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;
xAxis.TickLabelOffset = 200;
// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);
dataDir = dataDir + @"SetAxisProperties_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();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
// Fill data.
chart.Series.Add("AW Series 1",
new string[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" },
new double[] { 1.2, 0.3, 2.1, 2.9, 4.2 });
// Hide the Y axis.
chart.AxisY.Hidden = true;
dataDir = dataDir + @"HideChartAxis_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();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
// Fill data.
chart.Series.Add("AW Series 1",
new string[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" },
new double[] { 1.2, 0.3, 2.1, 2.9, 4.2 });
chart.AxisY.Scaling.Minimum = new AxisBound(0);
chart.AxisY.Scaling.Maximum = new AxisBound(6);
dataDir = dataDir + @"SetboundsOfAxis_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();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
// Fill data.
chart.Series.Add("AW Series 1",
new DateTime[] { new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29) },
new double[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });
// Set X axis bounds.
ChartAxis xAxis = chart.AxisX;
xAxis.Scaling.Minimum = new AxisBound((new DateTime(2017, 11, 05)).ToOADate());
xAxis.Scaling.Maximum = new AxisBound((new DateTime(2017, 12, 03)).ToOADate());
// Set major units to a week and minor units to a day.
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;
dataDir = dataDir + @"SetDateTimeValuesToAxis_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();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
// Fill data.
chart.Series.Add("AW Series 1",
new string[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" },
new double[] { 1.2, 0.3, 2.1, 2.9, 4.2 });
chart.AxisX.TickLabelSpacing = 2;
dataDir = dataDir + @"SetIntervalUnitBetweenLabelsOnAxis_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();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
// Fill data.
chart.Series.Add("AW Series 1",
new string[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" },
new double[] { 1900000, 850000, 2100000, 600000, 1500000 });
// Set number format.
chart.AxisY.NumberFormat.FormatCode = "#,##0";
dataDir = dataDir + @"FormatAxisNumber_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_WorkingWithCharts();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertChart(ChartType.Bar, 432, 252);
Chart chart = shape.Chart;
// Get first series.
ChartSeries series0 = shape.Chart.Series[0];
ChartDataLabelCollection dataLabelCollection = series0.DataLabels;
// Add data label to the first and second point of the first series.
ChartDataLabel chartDataLabel00 = dataLabelCollection.Add(0);
ChartDataLabel chartDataLabel01 = dataLabelCollection.Add(1);
// Set properties.
chartDataLabel00.ShowLegendKey = true;
// By default, when you add data labels to the data points in a pie chart, leader lines are displayed for data labels that are
// Positioned far outside the end of data points. Leader lines create a visual connection between a data label and its
// Corresponding data point.
chartDataLabel00.ShowLeaderLines = true;
chartDataLabel00.ShowCategoryName = false;
chartDataLabel00.ShowPercentage = false;
chartDataLabel00.ShowSeriesName = true;
chartDataLabel00.ShowValue = true;
chartDataLabel00.Separator = "/";
chartDataLabel01.ShowValue = true;
dataDir = dataDir + @"SimpleBarChart_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_WorkingWithCharts();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
// Get first series.
ChartSeries series0 = shape.Chart.Series[0];
// Get second series.
ChartSeries series1 = shape.Chart.Series[1];
ChartDataPointCollection dataPointCollection = series0.DataPoints;
// Add data point to the first and second point of the first series.
ChartDataPoint dataPoint00 = dataPointCollection.Add(0);
ChartDataPoint dataPoint01 = dataPointCollection.Add(1);
// Set explosion.
dataPoint00.Explosion = 50;
// Set marker symbol and size.
dataPoint00.Marker.Symbol = MarkerSymbol.Circle;
dataPoint00.Marker.Size = 15;
dataPoint01.Marker.Symbol = MarkerSymbol.Diamond;
dataPoint01.Marker.Size = 20;
// Add data point to the third point of the second series.
ChartDataPoint dataPoint12 = series1.DataPoints.Add(2);
dataPoint12.InvertIfNegative = true;
dataPoint12.Marker.Symbol = MarkerSymbol.Star;
dataPoint12.Marker.Size = 20;
dataDir = dataDir + @"SingleChartDataPoint_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Specifies whether by default the parent element shall inverts its colors if the value is negative.
series0.InvertIfNegative = true;
// Set default marker symbol and size.
series0.Marker.Symbol = MarkerSymbol.Circle;
series0.Marker.Size = 15;
series1.Marker.Symbol = MarkerSymbol.Star;
series1.Marker.Size = 10;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Get first series.
ChartSeries series0 = shape.Chart.Series[0];
// Get second series.
ChartSeries series1 = shape.Chart.Series[1];
// Change first series name.
series0.Name = "My Name1";
// Change second series name.
series1.Name = "My Name2";
// You can also specify whether the line connecting the points on the chart shall be smoothed using Catmull-Rom splines.
series0.Smooth = true;
series1.Smooth = true;
// 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_WorkingWithComments();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");
Comment comment = new Comment(doc, "Awais Hafeez", "AH", DateTime.Today);
builder.CurrentParagraph.AppendChild(comment);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
dataDir = dataDir + "Comments_out.doc";
// Save the document.
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("Some text is added.");
// 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_WorkingWithComments();
Document doc = new Document();
Paragraph para1 = new Paragraph(doc);
Run run1 = new Run(doc, "Some ");
Run run2 = new Run(doc, "text ");
para1.AppendChild(run1);
para1.AppendChild(run2);
doc.FirstSection.Body.AppendChild(para1);
Paragraph para2 = new Paragraph(doc);
Run run3 = new Run(doc, "is ");
Run run4 = new Run(doc, "added ");
para2.AppendChild(run3);
para2.AppendChild(run4);
doc.FirstSection.Body.AppendChild(para2);
Comment comment = new Comment(doc, "Awais Hafeez", "AH", DateTime.Today);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
CommentRangeStart commentRangeStart = new CommentRangeStart(doc, comment.Id);
CommentRangeEnd commentRangeEnd = new CommentRangeEnd(doc, comment.Id);
run1.ParentNode.InsertAfter(commentRangeStart, run1);
run3.ParentNode.InsertAfter(commentRangeEnd, run3);
commentRangeEnd.ParentNode.InsertAfter(comment, commentRangeEnd);
dataDir = dataDir + "Anchor.Comment_out.doc";
// Save the document.
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 + "TestFile.doc");
Comment comment = (Comment)doc.GetChild(NodeType.Comment, 0, true);
//Remove the reply
comment.RemoveReply(comment.Replies[0]);
//Add a reply to comment
comment.AddReply("John Doe", "JD", new DateTime(2017, 9, 25, 12, 15, 0), "New reply");
dataDir = dataDir + "TestFile_Out.doc";
// 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
static void CommentResolvedandReplies(Document doc)
{
NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);
Comment parentComment = (Comment)comments[0];
foreach (Comment childComment in parentComment.Replies)
{
// Get comment parent and status.
Console.WriteLine(childComment.Ancestor.Id);
Console.WriteLine(childComment.Done);
// And update comment Done mark.
childComment.Done = true;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
static ArrayList ExtractComments(Document doc)
{
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);
// Look through all comments and gather information about them.
foreach (Comment comment in comments)
{
collectedComments.Add(comment.Author + " " + comment.DateTime + " " + comment.ToString(SaveFormat.Text));
}
return collectedComments;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
static ArrayList ExtractComments(Document doc, string authorName)
{
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);
// Look through all comments and gather information about those written by the authorName author.
foreach (Comment comment in comments)
{
if (comment.Author == authorName)
collectedComments.Add(comment.Author + " " + comment.DateTime + " " + comment.ToString(SaveFormat.Text));
}
return collectedComments;
}
// 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_WorkingWithComments();
string fileName = "TestFile.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// Extract the information about the comments of all the authors.
foreach (string comment in ExtractComments(doc))
Console.Write(comment);
// Remove comments by the "pm" author.
RemoveComments(doc, "pm");
Console.WriteLine("Comments from \"pm\" are removed!");
// Extract the information about the comments of the "ks" author.
foreach (string comment in ExtractComments(doc, "ks"))
Console.Write(comment);
//Read the comment's reply and resolve them.
CommentResolvedandReplies(doc);
// Remove all comments.
RemoveComments(doc);
Console.WriteLine("All comments are removed!");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
static void RemoveComments(Document doc)
{
// Collect all comments in the document
NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);
// Remove all comments.
comments.Clear();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
static void RemoveComments(Document doc, string authorName)
{
// Collect all comments in the document
NodeCollection comments = doc.GetChildNodes(NodeType.Comment, true);
// Look through all comments and remove those written by the authorName author.
for (int i = comments.Count - 1; i >= 0; i--)
{
Comment comment = (Comment)comments[i];
if (comment.Author == authorName)
comment.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_WorkingWithComments();
string fileName = "TestFile.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
CommentRangeStart commentStart = (CommentRangeStart)doc.GetChild(NodeType.CommentRangeStart, 0, true);
CommentRangeEnd commentEnd = (CommentRangeEnd)doc.GetChild(NodeType.CommentRangeEnd, 0, true);
Node currentNode = commentStart;
Boolean isRemoving = true;
while (currentNode != null && isRemoving)
{
if (currentNode.NodeType == NodeType.CommentRangeEnd)
isRemoving = false;
Node nextNode = currentNode.NextPreOrder(doc);
currentNode.Remove();
currentNode = nextNode;
}
dataDir = dataDir + "RemoveRegionText_out.doc";
// Save the document.
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);
PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.InchToPoint(1.0);
pageSetup.BottomMargin = ConvertUtil.InchToPoint(1.0);
pageSetup.LeftMargin = ConvertUtil.InchToPoint(1.5);
pageSetup.RightMargin = ConvertUtil.InchToPoint(1.5);
pageSetup.HeaderDistance = ConvertUtil.InchToPoint(0.2);
pageSetup.FooterDistance = ConvertUtil.InchToPoint(0.2);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string text = "test\r";
// Replace "\r" control character with "\r\n"
text = text.Replace(ControlChar.Cr, ControlChar.CrLf);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
Document doc = new Document(dataDir + "Document.doc");
// Start tracking and make some revisions.
doc.StartTrackRevisions("Author");
doc.FirstSection.Body.AppendParagraph("Hello world!");
// Revisions will now show up as normal text in the output document.
doc.AcceptAllRevisions();
dataDir = dataDir + "Document.AcceptedRevisions_out.doc";
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_WorkingWithDocument();
// Load the template document.
Document doc = new Document(dataDir + "TestFile.doc");
// Get styles collection from document.
StyleCollection styles = doc.Styles;
string styleName = "";
// Iterate through all the styles.
foreach (Style style in styles)
{
if (styleName == "")
{
styleName = style.Name;
}
else
{
styleName = styleName + ", " + style.Name;
}
}
// 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_WorkingWithDocument();
Document doc = new Document();
doc.EnsureMinimum();
GroupShape gs = new GroupShape(doc);
Shape shape = new Shape(doc, Drawing.ShapeType.AccentBorderCallout1);
shape.Width = 100;
shape.Height = 100;
gs.AppendChild(shape);
Shape shape1 = new Shape(doc, Drawing.ShapeType.ActionButtonBeginning);
shape1.Left = 100;
shape1.Width = 100;
shape1.Height = 200;
gs.AppendChild(shape1);
gs.Width = 200;
gs.Height = 200;
gs.CoordSize = new System.Drawing.Size(200, 200);
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertNode(gs);
dataDir = dataDir + "groupshape-doc_out.doc";
// 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_WorkingWithDocument();
// Open the empty document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag SdtCheckBox = new StructuredDocumentTag(doc, SdtType.Checkbox, MarkupLevel.Inline);
// Insert content control into the document
builder.InsertNode(SdtCheckBox);
dataDir = dataDir + "CheckBoxTypeContentControl_out.docx";
doc.Save(dataDir, 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_WorkingWithDocument();
Document doc = new Document(dataDir + "Document.doc");
CleanupOptions cleanupoptions = new CleanupOptions();
cleanupoptions.UnusedLists = false;
cleanupoptions.UnusedStyles = true;
// Cleans unused styles and lists from the document depending on given CleanupOptions.
doc.Cleanup(cleanupoptions);
dataDir = dataDir + "Document.Cleanup_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_WorkingWithDocument();
// Load the document from disk.
Document doc = new Document(dataDir + "TestFile.doc");
Document clone = doc.Clone();
dataDir = dataDir + "TestFile_clone_out.doc";
// Save the document to disk.
clone.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_WorkingWithDocument();
Document doc = new Document();
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.ComboBox, MarkupLevel.Block);
sdt.ListItems.Add(new SdtListItem("Choose an item", "-1"));
sdt.ListItems.Add(new SdtListItem("Item 1", "1"));
sdt.ListItems.Add(new SdtListItem("Item 2", "2"));
doc.FirstSection.Body.AppendChild(sdt);
dataDir = dataDir + "ComboBoxContentControl_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static ArrayList ExtractContent(Node startNode, Node endNode, bool isInclusive)
{
// First check that the nodes passed to this method are valid for use.
VerifyParameterNodes(startNode, endNode);
// Create a list to store the extracted nodes.
ArrayList nodes = new ArrayList();
// Keep a record of the original nodes passed to this method so we can split marker nodes if needed.
Node originalStartNode = startNode;
Node originalEndNode = endNode;
// Extract content based on block level nodes (paragraphs and tables). Traverse through parent nodes to find them.
// We will split the content of first and last nodes depending if the marker nodes are inline
while (startNode.ParentNode.NodeType != NodeType.Body)
startNode = startNode.ParentNode;
while (endNode.ParentNode.NodeType != NodeType.Body)
endNode = endNode.ParentNode;
bool isExtracting = true;
bool isStartingNode = true;
bool isEndingNode = false;
// The current node we are extracting from the document.
Node currNode = startNode;
// Begin extracting content. Process all block level nodes and specifically split the first and last nodes when needed so paragraph formatting is retained.
// Method is little more complex than a regular extractor as we need to factor in extracting using inline nodes, fields, bookmarks etc as to make it really useful.
while (isExtracting)
{
// Clone the current node and its children to obtain a copy.
Node cloneNode = currNode.Clone(true);
isEndingNode = currNode.Equals(endNode);
if ((isStartingNode || isEndingNode) && cloneNode.IsComposite)
{
// We need to process each marker separately so pass it off to a separate method instead.
if (isStartingNode)
{
ProcessMarker((CompositeNode)cloneNode, nodes, originalStartNode, isInclusive, isStartingNode, isEndingNode);
isStartingNode = false;
}
// Conditional needs to be separate as the block level start and end markers maybe the same node.
if (isEndingNode)
{
ProcessMarker((CompositeNode)cloneNode, nodes, originalEndNode, isInclusive, isStartingNode, isEndingNode);
isExtracting = false;
}
}
else
// Node is not a start or end marker, simply add the copy to the list.
nodes.Add(cloneNode);
// Move to the next node and extract it. If next node is null that means the rest of the content is found in a different section.
if (currNode.NextSibling == null && isExtracting)
{
// Move to the next section.
Section nextSection = (Section)currNode.GetAncestor(NodeType.Section).NextSibling;
currNode = nextSection.Body.FirstChild;
}
else
{
// Move to the next node in the body.
currNode = currNode.NextSibling;
}
}
// Return the nodes between the node markers.
return nodes;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void VerifyParameterNodes(Node startNode, Node endNode)
{
// The order in which these checks are done is important.
if (startNode == null)
throw new ArgumentException("Start node cannot be null");
if (endNode == null)
throw new ArgumentException("End node cannot be null");
if (!startNode.Document.Equals(endNode.Document))
throw new ArgumentException("Start node and end node must belong to the same document");
if (startNode.GetAncestor(NodeType.Body) == null || endNode.GetAncestor(NodeType.Body) == null)
throw new ArgumentException("Start node and end node must be a child or descendant of a body");
// Check the end node is after the start node in the DOM tree
// First check if they are in different sections, then if they're not check their position in the body of the same section they are in.
Section startSection = (Section)startNode.GetAncestor(NodeType.Section);
Section endSection = (Section)endNode.GetAncestor(NodeType.Section);
int startIndex = startSection.ParentNode.IndexOf(startSection);
int endIndex = endSection.ParentNode.IndexOf(endSection);
if (startIndex == endIndex)
{
if (startSection.Body.IndexOf(startNode) > endSection.Body.IndexOf(endNode))
throw new ArgumentException("The end node must be after the start node in the body");
}
else if (startIndex > endIndex)
throw new ArgumentException("The section of end node must be after the section start node");
}
private static bool IsInline(Node node)
{
// Test if the node is desendant of a Paragraph or Table node and also is not a paragraph or a table a paragraph inside a comment class which is decesant of a pararaph is possible.
return ((node.GetAncestor(NodeType.Paragraph) != null || node.GetAncestor(NodeType.Table) != null) && !(node.NodeType == NodeType.Paragraph || node.NodeType == NodeType.Table));
}
private static void ProcessMarker(CompositeNode cloneNode, ArrayList nodes, Node node, bool isInclusive, bool isStartMarker, bool isEndMarker)
{
// If we are dealing with a block level node just see if it should be included and add it to the list.
if (!IsInline(node))
{
// Don't add the node twice if the markers are the same node
if (!(isStartMarker && isEndMarker))
{
if (isInclusive)
nodes.Add(cloneNode);
}
return;
}
// If a marker is a FieldStart node check if it's to be included or not.
// We assume for simplicity that the FieldStart and FieldEnd appear in the same paragraph.
if (node.NodeType == NodeType.FieldStart)
{
// If the marker is a start node and is not be included then skip to the end of the field.
// If the marker is an end node and it is to be included then move to the end field so the field will not be removed.
if ((isStartMarker && !isInclusive) || (!isStartMarker && isInclusive))
{
while (node.NextSibling != null && node.NodeType != NodeType.FieldEnd)
node = node.NextSibling;
}
}
// If either marker is part of a comment then to include the comment itself we need to move the pointer forward to the Comment
// Node found after the CommentRangeEnd node.
if (node.NodeType == NodeType.CommentRangeEnd)
{
while (node.NextSibling != null && node.NodeType != NodeType.Comment)
node = node.NextSibling;
}
// Find the corresponding node in our cloned node by index and return it.
// If the start and end node are the same some child nodes might already have been removed. Subtract the
// Difference to get the right index.
int indexDiff = node.ParentNode.ChildNodes.Count - cloneNode.ChildNodes.Count;
// Child node count identical.
if (indexDiff == 0)
node = cloneNode.ChildNodes[node.ParentNode.IndexOf(node)];
else
node = cloneNode.ChildNodes[node.ParentNode.IndexOf(node) - indexDiff];
// Remove the nodes up to/from the marker.
bool isSkip = false;
bool isProcessing = true;
bool isRemoving = isStartMarker;
Node nextNode = cloneNode.FirstChild;
while (isProcessing && nextNode != null)
{
Node currentNode = nextNode;
isSkip = false;
if (currentNode.Equals(node))
{
if (isStartMarker)
{
isProcessing = false;
if (isInclusive)
isRemoving = false;
}
else
{
isRemoving = true;
if (isInclusive)
isSkip = true;
}
}
nextNode = nextNode.NextSibling;
if (isRemoving && !isSkip)
currentNode.Remove();
}
// After processing the composite node may become empty. If it has don't include it.
if (!(isStartMarker && isEndMarker))
{
if (cloneNode.HasChildNodes)
nodes.Add(cloneNode);
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static Document GenerateDocument(Document srcDoc, ArrayList nodes)
{
// Create a blank document.
Document dstDoc = new Document();
// Remove the first paragraph from the empty document.
dstDoc.FirstSection.Body.RemoveAllChildren();
// Import each node from the list into the new document. Keep the original formatting of the node.
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting);
foreach (Node node in nodes)
{
Node importNode = importer.ImportNode(node, true);
dstDoc.FirstSection.Body.AppendChild(importNode);
}
// Return the generated document.
return dstDoc;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
CompareOptions options = new CompareOptions();
options.IgnoreFormatting = true;
options.IgnoreHeadersAndFooters = true;
options.IgnoreCaseChanges = true;
options.IgnoreTables = true;
options.IgnoreFields = true;
options.IgnoreComments = true;
options.IgnoreTextboxes = true;
options.IgnoreFootnotes = true;
// DocA now contains changes as revisions.
docA.Compare(docB, "user", DateTime.Now, options);
if (docA.Revisions.Count == 0)
Console.WriteLine("Documents are equal");
else
Console.WriteLine("Documents are not equal");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
CompareOptions options = new CompareOptions();
options.IgnoreFormatting = true;
// Relates to Microsoft Word "Show changes in" option in "Compare Documents" dialog box.
options.Target = ComparisonTargetType.New;
docA.Compare(docB, "user", DateTime.Now, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
// DocA now contains changes as revisions.
docA.Compare(docB, "user", DateTime.Now);
if (docA.Revisions.Count == 0)
Console.WriteLine("Documents are equal");
else
Console.WriteLine("Documents are not equal");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
// DocA now contains changes as revisions.
docA.Compare(docB, "user", DateTime.Now);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Clones and copies headers/footers form the previous section to the specified section.
/// </summary>
private static void CopyHeadersFootersFromPreviousSection(Section section)
{
Section previousSection = (Section)section.PreviousSibling;
if (previousSection == null)
return;
section.HeadersFooters.Clear();
foreach (HeaderFooter headerFooter in previousSection.HeadersFooters)
section.HeadersFooters.Add(headerFooter.Clone(true));
}
// 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_WorkingWithDocument();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Section currentSection = builder.CurrentSection;
PageSetup pageSetup = currentSection.PageSetup;
// Specify if we want headers/footers of the first page to be different from other pages.
// You can also use PageSetup.OddAndEvenPagesHeaderFooter property to specify
// Different headers/footers for odd and even pages.
pageSetup.DifferentFirstPageHeaderFooter = true;
// --- Create header for the first page. ---
pageSetup.HeaderDistance = 20;
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// Set font properties for header text.
builder.Font.Name = "Arial";
builder.Font.Bold = true;
builder.Font.Size = 14;
// Specify header title for the first page.
builder.Write("Aspose.Words Header/Footer Creation Primer - Title Page.");
// --- Create header for pages other than first. ---
pageSetup.HeaderDistance = 20;
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
// Insert absolutely positioned image into the top/left corner of the header.
// Distance from the top/left edges of the page is set to 10 points.
string imageFileName = dataDir + "Aspose.Words.gif";
builder.InsertImage(imageFileName, RelativeHorizontalPosition.Page, 10, RelativeVerticalPosition.Page, 10, 50, 50, WrapType.Through);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
// Specify another header title for other pages.
builder.Write("Aspose.Words Header/Footer Creation Primer.");
// --- Create footer for pages other than first. ---
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
// We use table with two cells to make one part of the text on the line (with page numbering)
// To be aligned left, and the other part of the text (with copyright) to be aligned right.
builder.StartTable();
// Clear table borders.
builder.CellFormat.ClearFormatting();
builder.InsertCell();
// Set first cell to 1/3 of the page width.
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100 / 3);
// Insert page numbering text here.
// It uses PAGE and NUMPAGES fields to auto calculate current page number and total number of pages.
builder.Write("Page ");
builder.InsertField("PAGE", "");
builder.Write(" of ");
builder.InsertField("NUMPAGES", "");
// Align this text to the left.
builder.CurrentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.InsertCell();
// Set the second cell to 2/3 of the page width.
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100 * 2 / 3);
builder.Write("(C) 2001 Aspose Pty Ltd. All rights reserved.");
// Align this text to the right.
builder.CurrentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.EndRow();
builder.EndTable();
builder.MoveToDocumentEnd();
// Make page break to create a second page on which the primary headers/footers will be seen.
builder.InsertBreak(BreakType.PageBreak);
// Make section break to create a third page with different page orientation.
builder.InsertBreak(BreakType.SectionBreakNewPage);
// Get the new section and its page setup.
currentSection = builder.CurrentSection;
pageSetup = currentSection.PageSetup;
// Set page orientation of the new section to landscape.
pageSetup.Orientation = Orientation.Landscape;
// This section does not need different first page header/footer.
// We need only one title page in the document and the header/footer for this page
// Has already been defined in the previous section
pageSetup.DifferentFirstPageHeaderFooter = false;
// This section displays headers/footers from the previous section by default.
// Call currentSection.HeadersFooters.LinkToPrevious(false) to cancel this.
// Page width is different for the new section and therefore we need to set
// A different cell widths for a footer table.
currentSection.HeadersFooters.LinkToPrevious(false);
// If we want to use the already existing header/footer set for this section
// But with some minor modifications then it may be expedient to copy headers/footers
// From the previous section and apply the necessary modifications where we want them.
CopyHeadersFootersFromPreviousSection(currentSection);
// Find the footer that we want to change.
HeaderFooter primaryFooter = currentSection.HeadersFooters[HeaderFooterType.FooterPrimary];
Row row = primaryFooter.Tables[0].FirstRow;
row.FirstCell.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100 / 3);
row.LastCell.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100 * 2 / 3);
dataDir = dataDir + "HeaderFooter.Primer_out.doc";
// Save the resulting document.
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 + "Properties.doc");
CustomDocumentProperties props = doc.CustomDocumentProperties;
if (props["Authorized"] == null)
{
props.Add("Authorized", true);
props.Add("Authorized By", "John Smith");
props.Add("Authorized Date", DateTime.Today);
props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
props.Add("Authorized Amount", 123.45);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Properties.doc");
doc.CustomDocumentProperties.Remove("Authorized Date");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string fileName = dataDir + "Properties.doc";
Document doc = new Document(fileName);
Console.WriteLine("1. Document name: {0}", fileName);
Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty prop in doc.BuiltInDocumentProperties)
Console.WriteLine("{0} : {1}", prop.Name, prop.Value);
Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty prop in doc.CustomDocumentProperties)
Console.WriteLine("{0} : {1}", prop.Name, prop.Value);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Properties.doc");
doc.RemovePersonalInformation = true;
dataDir = dataDir + "RemovePersonalInformation_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_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");
// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");
builder.EndRow();
// Insert a cell
builder.InsertCell();
// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;
builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");
// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");
builder.EndRow();
builder.EndTable();
dataDir = dataDir + "DocumentBuilderBuildTable_out.doc";
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_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartBookmark("FineBookmark");
builder.Writeln("This is just a fine bookmark.");
builder.EndBookmark("FineBookmark");
dataDir = dataDir + "DocumentBuilderInsertBookmark_out.doc";
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_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("This is page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("This is page 2.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("This is page 3.");
dataDir = dataDir + "DocumentBuilderInsertBreak_out.doc";
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.InsertCheckBox("CheckBox", true, true, 0);
dataDir = dataDir + "DocumentBuilderInsertCheckBoxFormField_out.doc";
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);
string[] items = { "One", "Two", "Three" };
builder.InsertComboBox("DropDown", items, 0);
dataDir = dataDir + "DocumentBuilderInsertComboBoxFormField_out.doc";
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.InsertHtml(
"<P align='right'>Paragraph right</P>" +
"<b>Implicit paragraph left</b>" +
"<div align='center'>Div center</div>" +
"<h1 align='left'>Heading 1 left.</h1>");
dataDir = dataDir + "DocumentBuilderInsertHtml_out.doc";
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.InsertOleObject("http://www.aspose.com", "htmlfile", true, true, null);
dataDir = dataDir + "DocumentBuilderInsertOleObject_out.doc";
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);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("Heading 1");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("Heading 2");
builder.Writeln("Heading 3");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 3.1");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;
builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");
doc.UpdateFields();
dataDir = dataDir + "DocumentBuilderInsertTableOfContents_out.doc";
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.InsertTextInput("TextInput", TextFormFieldType.Regular, "", "Hello", 0);
dataDir = dataDir + "DocumentBuilderInsertTextInputFormField_out.doc";
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);
byte[] bs = File.ReadAllBytes(dataDir + @"input.zip");
using (Stream stream = new MemoryStream(bs))
{
Shape shape = builder.InsertOleObject(stream, "Package", true, null);
OlePackage olePackage = shape.OleFormat.OlePackage;
olePackage.FileName = "filename.zip";
olePackage.DisplayName = "displayname.zip";
dataDir = dataDir + "DocumentBuilderInsertOleObjectOlePackage_out.doc";
doc.Save(dataDir);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Insert a horizontal rule shape into the document.");
builder.InsertHorizontalRule();
dataDir = dataDir + "DocumentBuilder.InsertHorizontalRule_out.doc";
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.InsertImage(dataDir + "Watermark.png",
RelativeHorizontalPosition.Margin,
100,
RelativeVerticalPosition.Margin,
100,
200,
100,
WrapType.Square);
dataDir = dataDir + "DocumentBuilderInsertFloatingImage_out.doc";
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.InsertImage(dataDir + "Watermark.png");
dataDir = dataDir + "DocumentBuilderInsertInlineImage_out.doc";
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_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify font formatting
Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = System.Drawing.Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;
// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.KeepTogether = true;
builder.Writeln("A whole paragraph.");
dataDir = dataDir + "DocumentBuilderInsertParagraph_out.doc";
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_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
// Create a document builder to insert content with.
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a TC field at the current document builder position.
builder.InsertField("TC \"Entry Text\" \\f t");
dataDir = dataDir + "DocumentBuilderInsertTCField_out.doc";
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();
FindReplaceOptions options = new FindReplaceOptions();
// Highlight newly inserted content.
options.ApplyFont.HighlightColor = Color.DarkOrange;
options.ReplacingCallback = new InsertTCFieldHandler("Chapter 1", "\\l 1");
// Insert a TC field which displays "Chapter 1" just before the text "The Beginning" in the document.
doc.Range.Replace(new Regex("The Beginning"), "", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public sealed class InsertTCFieldHandler : IReplacingCallback
{
// Store the text and switches to be used for the TC fields.
private string mFieldText;
private string mFieldSwitches;
/// <summary>
/// The switches to use for each TC field. Can be an empty string or null.
/// </summary>
public InsertTCFieldHandler(string switches)
: this(string.Empty, switches)
{
mFieldSwitches = switches;
}
/// <summary>
/// The display text and switches to use for each TC field. Display name can be an empty string or null.
/// </summary>
public InsertTCFieldHandler(string text, string switches)
{
mFieldText = text;
mFieldSwitches = switches;
}
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
{
// Create a builder to insert the field.
DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
// Move to the first node of the match.
builder.MoveTo(args.MatchNode);
// If the user specified text to be used in the field as display text then use that, otherwise use the
// Match string as the display text.
string insertText;
if (!string.IsNullOrEmpty(mFieldText))
insertText = mFieldText;
else
insertText = args.Match.Value;
// Insert the TC field before this node using the specified string as the display text and user defined switches.
builder.InsertField(string.Format("TC \"{0}\" {1}", insertText, mFieldSwitches));
// We have done what we want so skip replacement.
return ReplaceAction.Skip;
}
}
// 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_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// The newly inserted table of contents will be initially empty.
// It needs to be populated by updating the fields in the document.
doc.UpdateFields();
dataDir = dataDir + "DocumentBuilderInsertTOC_out.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
doc.UpdateFields();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Shows how to access the current node in a document builder.
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
Node curNode = builder.CurrentNode;
Paragraph curParagraph = builder.CurrentParagraph;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;
// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");
// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");
dataDir = dataDir + "DocumentBuilder.HeadersAndFooters_out.doc";
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 + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToBookmark("CoolBookmark");
builder.Writeln("This is a very cool bookmark.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToBookmark("CoolBookmark", false, true);
builder.Writeln("This is a very cool bookmark.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
Console.WriteLine("\nThis is the end of the document.");
builder.MoveToDocumentStart();
Console.WriteLine("\nThis is the beginning of the document.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField("NiceMergeField");
builder.Writeln("This is a very nice merge field.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveTo(doc.FirstSection.Body.LastParagraph);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Parameters are 0-index. Moves to third paragraph.
builder.MoveToParagraph(2, 0);
builder.Writeln("This is the 3rd paragraph.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Parameters are 0-index. Moves to third section.
builder.MoveToSection(2);
builder.Writeln("This is the 3rd section.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// All parameters are 0-index. Moves to the 2nd table, 3rd row, 5th cell.
builder.MoveToCell(1, 2, 4, 0);
builder.Writeln("Hello World!");
// 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);
// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;
// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;
builder.Write("I'm a formatted paragraph with double border and nice shading.");
dataDir = dataDir + "DocumentBuilderApplyBordersAndShadingToParagraph_out.doc";
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);
// Set paragraph style
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Title;
builder.Write("Hello");
dataDir = dataDir + "DocumentBuilderApplyParagraphStyle_out.doc";
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);
// Set font formatting properties
Font font = builder.Font;
font.Bold = true;
font.Color = System.Drawing.Color.DarkBlue;
font.Italic = true;
font.Name = "Arial";
font.Size = 24;
font.Spacing = 5;
font.Underline = Underline.Double;
// Output formatted text
builder.Writeln("I'm a very nice formatted string.");
dataDir = dataDir + "DocumentBuilderSetFontFormatting_out.doc";
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.ListFormat.ApplyNumberDefault();
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.ListIndent();
builder.Writeln("Item 2.1");
builder.Writeln("Item 2.2");
builder.ListFormat.ListIndent();
builder.Writeln("Item 2.2.1");
builder.Writeln("Item 2.2.2");
builder.ListFormat.ListOutdent();
builder.Writeln("Item 2.3");
builder.ListFormat.ListOutdent();
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
dataDir = dataDir + "DocumentBuilderSetMultilevelListFormatting_out.doc";
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);
// Set page properties
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.LeftMargin = 50;
builder.PageSetup.PaperSize = PaperSize.Paper10x14;
dataDir = dataDir + "DocumentBuilderSetPageSetupAndSectionFormatting_out.doc";
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);
// Set paragraph formatting properties
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphFormat.LeftIndent = 50;
paragraphFormat.RightIndent = 50;
paragraphFormat.SpaceAfter = 25;
// Output text
builder.Writeln("I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
builder.Writeln("I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");
dataDir = dataDir + "DocumentBuilderSetParagraphFormatting_out.doc";
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);
// Set paragraph formatting properties
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.AddSpaceBetweenFarEastAndAlpha = true;
paragraphFormat.AddSpaceBetweenFarEastAndDigit = true;
builder.Writeln("Automatically adjust space between Asian and Latin text");
builder.Writeln("Automatically adjust space between Asian text and numbers");
dataDir = dataDir + "DocumentBuilderSetSpacebetweenAsianandLatintext.doc";
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.StartTable();
builder.InsertCell();
// Set the cell formatting
CellFormat cellFormat = builder.CellFormat;
cellFormat.Width = 250;
cellFormat.LeftPadding = 30;
cellFormat.RightPadding = 30;
cellFormat.TopPadding = 30;
cellFormat.BottomPadding = 30;
builder.Writeln("I'm a wonderful formatted cell.");
builder.EndRow();
builder.EndTable();
dataDir = dataDir + "DocumentBuilderSetTableCellFormatting_out.doc";
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);
Table table = builder.StartTable();
builder.InsertCell();
// Set the row formatting
RowFormat rowFormat = builder.RowFormat;
rowFormat.Height = 100;
rowFormat.HeightRule = HeightRule.Exactly;
// These formatting properties are set on the table and are applied to all rows in the table.
table.LeftPadding = 30;
table.RightPadding = 30;
table.TopPadding = 30;
table.BottomPadding = 30;
builder.Writeln("I'm a wonderful formatted row.");
builder.EndRow();
builder.EndTable();
dataDir = dataDir + "DocumentBuilderSetTableRowFormatting_out.doc";
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 + "Input.docx");
ParagraphFormat format = doc.FirstSection.Body.Paragraphs[0].ParagraphFormat;
format.FarEastLineBreakControl = false;
format.WordWrap = true;
format.HangingPunctuation = false;
dataDir = dataDir + "SetAsianTypographyLinebreakGroupProp_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_WorkingWithDocument();
Document doc = new Document(dataDir + "Document.doc");
//Set the layout mode for a section allowing to define the document grid behavior
//Note that the Document Grid tab becomes visible in the Page Setup dialog of MS Word if any Asian language is defined as editing language.
doc.FirstSection.PageSetup.LayoutMode = SectionLayoutMode.Grid;
//Set the number of characters per line in the document grid.
doc.FirstSection.PageSetup.CharactersPerLine = 30;
//Set the number of lines per page in the document grid.
doc.FirstSection.PageSetup.LinesPerPage = 10;
dataDir = dataDir + "Document.PageSetup_out.doc";
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_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
Paragraph startPara = (Paragraph)doc.LastSection.GetChild(NodeType.Paragraph, 2, true);
Table endTable = (Table)doc.LastSection.GetChild(NodeType.Table, 0, true);
// Extract the content between these nodes in the document. Include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startPara, endTable, true);
// Lets reverse the array to make inserting the content back into the document easier.
extractedNodes.Reverse();
while (extractedNodes.Count > 0)
{
// Insert the last node from the reversed list
endTable.ParentNode.InsertAfter((Node)extractedNodes[0], endTable);
// Remove this node from the list after insertion.
extractedNodes.RemoveAt(0);
}
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the generated 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_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
Section section = doc.Sections[0];
section.PageSetup.LeftMargin = 70.85;
// Retrieve the bookmark from the document.
Bookmark bookmark = doc.Range.Bookmarks["Bookmark1"];
// We use the BookmarkStart and BookmarkEnd nodes as markers.
BookmarkStart bookmarkStart = bookmark.BookmarkStart;
BookmarkEnd bookmarkEnd = bookmark.BookmarkEnd;
// Firstly extract the content between these nodes including the bookmark.
ArrayList extractedNodesInclusive = Common.ExtractContent(bookmarkStart, bookmarkEnd, true);
Document dstDoc = Common.GenerateDocument(doc, extractedNodesInclusive);
dstDoc.Save(dataDir + "TestFile.BookmarkInclusive_out.doc");
// Secondly extract the content between these nodes this time without including the bookmark.
ArrayList extractedNodesExclusive = Common.ExtractContent(bookmarkStart, bookmarkEnd, false);
dstDoc = Common.GenerateDocument(doc, extractedNodesExclusive);
dstDoc.Save(dataDir + "TestFile.BookmarkExclusive_out.doc");
// 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_WorkingWithDocument();
Document doc = new Document(dataDir + "TestFile.doc");
// This is a quick way of getting both comment nodes.
// Your code should have a proper method of retrieving each corresponding start and end node.
CommentRangeStart commentStart = (CommentRangeStart)doc.GetChild(NodeType.CommentRangeStart, 0, true);
CommentRangeEnd commentEnd = (CommentRangeEnd)doc.GetChild(NodeType.CommentRangeEnd, 0, true);
// Firstly extract the content between these nodes including the comment as well.
ArrayList extractedNodesInclusive = Common.ExtractContent(commentStart, commentEnd, true);
Document dstDoc = Common.GenerateDocument(doc, extractedNodesInclusive);
dstDoc.Save(dataDir + "TestFile.CommentInclusive_out.doc");
// Secondly extract the content between these nodes without the comment.
ArrayList extractedNodesExclusive = Common.ExtractContent(commentStart, commentEnd, false);
dstDoc = Common.GenerateDocument(doc, extractedNodesExclusive);
dstDoc.Save(dataDir + "TestFile.CommentExclusive_out.doc");
// 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_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Gather the nodes. The GetChild method uses 0-based index
Paragraph startPara = (Paragraph)doc.FirstSection.Body.GetChild(NodeType.Paragraph, 6, true);
Paragraph endPara = (Paragraph)doc.FirstSection.Body.GetChild(NodeType.Paragraph, 10, true);
// Extract the content between these nodes in the document. Include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startPara, endPara, true);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.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_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Gather a list of the paragraphs using the respective heading styles.
ArrayList parasStyleHeading1 = Common.ParagraphsByStyleName(doc, "Heading 1");
ArrayList parasStyleHeading3 = Common.ParagraphsByStyleName(doc, "Heading 3");
// Use the first instance of the paragraphs with those styles.
Node startPara1 = (Node)parasStyleHeading1[0];
Node endPara1 = (Node)parasStyleHeading3[0];
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startPara1, endPara1, false);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.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_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Retrieve a paragraph from the first section.
Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 7, true);
// Use some runs for extraction.
Run startRun = para.Runs[1];
Run endRun = para.Runs[4];
// Extract the content between these nodes in the document. Include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startRun, endRun, true);
// Get the node from the list. There should only be one paragraph returned in the list.
Node node = (Node)extractedNodes[0];
// Print the text of this node to the console.
Console.WriteLine(node.ToString(SaveFormat.Text));
// 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_WorkingWithDocument();
// Open the document we want to convert.
Document doc = new Document(dataDir + "Visitor.ToText.doc");
// Create an object that inherits from the DocumentVisitor class.
MyDocToTxtWriter myConverter = new MyDocToTxtWriter();
// This is the well known Visitor pattern. Get the model to accept a visitor.
// The model will iterate through itself by calling the corresponding methods
// On the visitor object (this is called visiting).
//
// Note that every node in the object model has the Accept method so the visiting
// Can be executed not only for the whole document, but for any node in the document.
doc.Accept(myConverter);
// Once the visiting is complete, we can retrieve the result of the operation,
// That in this example, has accumulated in the visitor.
Console.WriteLine(myConverter.GetText());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
internal class MyDocToTxtWriter : DocumentVisitor
{
public MyDocToTxtWriter()
{
mIsSkipText = false;
mBuilder = new StringBuilder();
}
/// <summary>
/// Gets the plain text of the document that was accumulated by the visitor.
/// </summary>
public string GetText()
{
return mBuilder.ToString();
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// </summary>
public override VisitorAction VisitRun(Run run)
{
AppendText(run.Text);
// Let the visitor continue visiting other nodes.
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldStart node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldStart(FieldStart fieldStart)
{
// In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
// After a field start character. We want to skip field codes and output field
// Result only, therefore we use a flag to suspend the output while inside a field code.
//
// Note this is a very simplistic implementation and will not work very well
// If you have nested fields in a document.
mIsSkipText = true;
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldSeparator node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
{
// Once reached a field separator node, we enable the output because we are
// Now entering the field result nodes.
mIsSkipText = false;
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldEnd node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
{
// Make sure we enable the output when reached a field end because some fields
// Do not have field separator and do not have field result.
mIsSkipText = false;
return VisitorAction.Continue;
}
/// <summary>
/// Called when visiting of a Paragraph node is ended in the document.
/// </summary>
public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
{
// When outputting to plain text we output Cr+Lf characters.
AppendText(ControlChar.CrLf);
return VisitorAction.Continue;
}
public override VisitorAction VisitBodyStart(Body body)
{
// We can detect beginning and end of all composite nodes such as Section, Body,
// Table, Paragraph etc and provide custom handling for them.
mBuilder.Append("*** Body Started ***\r\n");
return VisitorAction.Continue;
}
public override VisitorAction VisitBodyEnd(Body body)
{
mBuilder.Append("*** Body Ended ***\r\n");
return VisitorAction.Continue;
}
/// <summary>
/// Called when a HeaderFooter node is encountered in the document.
/// </summary>
public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
{
// Returning this value from a visitor method causes visiting of this
// Node to stop and move on to visiting the next sibling node.
// The net effect in this example is that the text of headers and footers
// Is not included in the resulting output.
return VisitorAction.SkipThisNode;
}
/// <summary>
/// Adds text to the current output. Honours the enabled/disabled output flag.
/// </summary>
private void AppendText(string text)
{
if (!mIsSkipText)
mBuilder.Append(text);
}
private readonly StringBuilder mBuilder;
private bool mIsSkipText;
}
// 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_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Use a document builder to retrieve the field start of a merge field.
DocumentBuilder builder = new DocumentBuilder(doc);
// Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field.
// We could also get FieldStarts of a field using GetChildNode method as in the other examples.
builder.MoveToMergeField("Fullname", false, false);
// The builder cursor should be positioned at the start of the field.
FieldStart startField = (FieldStart)builder.CurrentNode;
Paragraph endPara = (Paragraph)doc.FirstSection.GetChild(NodeType.Paragraph, 5, true);
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startField, endPara, false);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Enter a dummy field into the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField("MERGEFIELD Field");
// GetText will retrieve all field codes and special characters
Console.WriteLine("GetText() Result: " + doc.GetText());
// ToString will export the node to the specified format. When converted to text it will not retrieve fields code
// Or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
// This is the same as "viewing" the document as if it was opened in a text editor.
Console.WriteLine("ToString() Result: " + doc.ToString(SaveFormat.Text));
// 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_WorkingWithDocument();
Document doc = new Document(dataDir + @"GenerateACustomBarCodeImage.docx");
// Set custom barcode generator
doc.FieldOptions.BarcodeGenerator = new CustomBarcodeGenerator();
doc.Save(dataDir + @"GenerateACustomBarCodeImage_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class CustomBarcodeGenerator : IBarcodeGenerator
{
/// <summary>
/// Converts barcode image height from Word units to Aspose.BarCode units.
/// </summary>
/// <param name="heightInTwipsString"></param>
/// <returns></returns>
private static float ConvertSymbolHeight(string heightInTwipsString)
{
// Input value is in 1/1440 inches (twips)
int heightInTwips = int.MinValue;
int.TryParse(heightInTwipsString, out heightInTwips);
if (heightInTwips == int.MinValue)
throw new Exception("Error! Incorrect height - " + heightInTwipsString + ".");
// Convert to mm
return (float)(heightInTwips * 25.4 / 1440);
}
/// <summary>
/// Converts barcode image color from Word to Aspose.BarCode.
/// </summary>
/// <param name="inputColor"></param>
/// <returns></returns>
private static Color ConvertColor(string inputColor)
{
// Input should be from "0x000000" to "0xFFFFFF"
int color = int.MinValue;
int.TryParse(inputColor.Replace("0x", ""), out color);
if (color == int.MinValue)
throw new Exception("Error! Incorrect color - " + inputColor + ".");
return Color.FromArgb(color >> 16, (color & 0xFF00) >> 8, color & 0xFF);
// Backword conversion -
//return string.Format("0x{0,6:X6}", mControl.ForeColor.ToArgb() & 0xFFFFFF);
}
/// <summary>
/// Converts bar code scaling factor from percents to float.
/// </summary>
/// <param name="scalingFactor"></param>
/// <returns></returns>
private static float ConvertScalingFactor(string scalingFactor)
{
bool isParsed = false;
int percents = int.MinValue;
int.TryParse(scalingFactor, out percents);
if (percents != int.MinValue)
{
if (percents >= 10 && percents <= 10000)
isParsed = true;
}
if (!isParsed)
throw new Exception("Error! Incorrect scaling factor - " + scalingFactor + ".");
return percents / 100.0f;
}
/// <summary>
/// Implementation of the GetBarCodeImage() method for IBarCodeGenerator interface.
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public Image GetBarcodeImage(BarcodeParameters parameters)
{
if (parameters.BarcodeType == null || parameters.BarcodeValue == null)
return null;
BarCodeBuilder builder = new BarCodeBuilder();
string type = parameters.BarcodeType.ToUpper();
switch (type)
{
case "QR":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.QR;
break;
case "CODE128":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.Code128;
break;
case "CODE39":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.Code39Standard;
break;
case "EAN8":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.EAN8;
break;
case "EAN13":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.EAN13;
break;
case "UPCA":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.UPCA;
break;
case "UPCE":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.UPCE;
break;
case "ITF14":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.ITF14;
break;
case "CASE":
builder.EncodeType = Aspose.BarCode.Generation.EncodeTypes.None;
break;
}
//builder.EncodeType = ConvertBarcodeType(parameters.BarcodeType);
if (builder.EncodeType == Aspose.BarCode.Generation.EncodeTypes.None)
return null;
builder.CodeText = parameters.BarcodeValue;
if (builder.EncodeType == Aspose.BarCode.Generation.EncodeTypes.QR)
builder.Display2DText = parameters.BarcodeValue;
if (parameters.ForegroundColor != null)
builder.ForeColor = ConvertColor(parameters.ForegroundColor);
if (parameters.BackgroundColor != null)
builder.BackColor = ConvertColor(parameters.BackgroundColor);
if (parameters.SymbolHeight != null)
{
builder.ImageHeight = ConvertSymbolHeight(parameters.SymbolHeight);
builder.AutoSize = false;
}
builder.CodeLocation = CodeLocation.None;
if (parameters.DisplayText)
builder.CodeLocation = CodeLocation.Below;
builder.CaptionAbove.Text = "";
const float scale = 0.4f; // Empiric scaling factor for converting Word barcode to Aspose.BarCode
float xdim = 1.0f;
if (builder.EncodeType == Aspose.BarCode.Generation.EncodeTypes.QR)
{
builder.AutoSize = false;
builder.ImageWidth *= scale;
builder.ImageHeight = builder.ImageWidth;
xdim = builder.ImageHeight / 25;
builder.xDimension = builder.yDimension = xdim;
}
if (parameters.ScalingFactor != null)
{
float scalingFactor = ConvertScalingFactor(parameters.ScalingFactor);
builder.ImageHeight *= scalingFactor;
if (builder.EncodeType == Aspose.BarCode.Generation.EncodeTypes.QR)
{
builder.ImageWidth = builder.ImageHeight;
builder.xDimension = builder.yDimension = xdim * scalingFactor;
}
builder.AutoSize = false;
}
return builder.BarCodeImage;
}
//Image IBarcodeGenerator.GetBarcodeImage(BarcodeParameters parameters)
//{
// throw new NotImplementedException();
//}
public Image GetOldBarcodeImage(BarcodeParameters parameters)
{
throw new NotImplementedException();
}
}
// 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_WorkingWithDocument();
// Load the template document.
Document doc = new Document(dataDir + "TestFile.doc");
string variables = "";
foreach (KeyValuePair<string, string> entry in doc.Variables)
{
string name = entry.Key.ToString();
string value = entry.Value.ToString();
if (variables == "")
{
// Do something useful.
variables = "Name: " + name + "," + "Value: {1}" + value;
}
else
{
variables = variables + "Name: " + name + "," + "Value: {1}" + value;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// Should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
static void InsertDocument(Node insertAfterNode, Document srcDoc)
{
// Make sure that the node is either a paragraph or table.
if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
(!insertAfterNode.NodeType.Equals(NodeType.Table)))
throw new ArgumentException("The destination node should be either a paragraph or table.");
// We will be inserting into the parent of the destination paragraph.
CompositeNode dstStory = insertAfterNode.ParentNode;
// This object will be translating styles and lists during the import.
NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);
// Loop through all sections in the source document.
foreach (Section srcSection in srcDoc.Sections)
{
// Loop through all block level nodes (paragraphs and tables) in the body of the section.
foreach (Node srcNode in srcSection.Body)
{
// Let's skip the node if it is a last empty paragraph in a section.
if (srcNode.NodeType.Equals(NodeType.Paragraph))
{
Paragraph para = (Paragraph)srcNode;
if (para.IsEndOfSection && !para.HasChildNodes)
continue;
}
// This creates a clone of the node, suitable for insertion into the destination document.
Node newNode = importer.ImportNode(srcNode, true);
// Insert new node after the reference node.
dstStory.InsertAfter(newNode, insertAfterNode);
insertAfterNode = newNode;
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document mainDoc = new Document(dataDir + "InsertDocument1.doc");
Document subDoc = new Document(dataDir + "InsertDocument2.doc");
Bookmark bookmark = mainDoc.Range.Bookmarks["insertionPlace"];
InsertDocument(bookmark.BookmarkStart.ParentNode, subDoc);
dataDir = dataDir + "InsertDocumentAtBookmark_out.doc";
mainDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open the main document.
Document mainDoc = new Document(dataDir + "InsertDocument1.doc");
// Add a handler to MergeField event
mainDoc.MailMerge.FieldMergingCallback = new InsertDocumentAtMailMergeHandler();
// The main document has a merge field in it called "Document_1".
// The corresponding data for this field contains fully qualified path to the document
// That should be inserted to this field.
mainDoc.MailMerge.Execute(
new string[] { "Document_1" },
new string[] { dataDir + "InsertDocument2.doc" });
dataDir = dataDir + "InsertDocumentAtMailMerge_out.doc";
mainDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class InsertDocumentAtMailMergeBlobHandler : IFieldMergingCallback
{
/// <summary>
/// This handler makes special processing for the "Document_1" field.
/// The field value contains the path to load the document.
/// We load the document and insert it into the current merge field.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (e.DocumentFieldName == "Document_1")
{
// Use document builder to navigate to the merge field with the specified name.
DocumentBuilder builder = new DocumentBuilder(e.Document);
builder.MoveToMergeField(e.DocumentFieldName);
// Load the document from the blob field.
MemoryStream stream = new MemoryStream((byte[])e.FieldValue);
Document subDoc = new Document(stream);
// Insert the document.
InsertDocument(builder.CurrentParagraph, subDoc);
// The paragraph that contained the merge field might be empty now and you probably want to delete it.
if (!builder.CurrentParagraph.HasChildNodes)
builder.CurrentParagraph.Remove();
// Indicate to the mail merge engine that we have inserted what we wanted.
e.Text = null;
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class InsertDocumentAtMailMergeHandler : IFieldMergingCallback
{
/// <summary>
/// This handler makes special processing for the "Document_1" field.
/// The field value contains the path to load the document.
/// We load the document and insert it into the current merge field.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (e.DocumentFieldName == "Document_1")
{
// Use document builder to navigate to the merge field with the specified name.
DocumentBuilder builder = new DocumentBuilder(e.Document);
builder.MoveToMergeField(e.DocumentFieldName);
// The name of the document to load and insert is stored in the field value.
Document subDoc = new Document((string)e.FieldValue);
// Insert the document.
InsertDocument(builder.CurrentParagraph, subDoc);
// The paragraph that contained the merge field might be empty now and you probably want to delete it.
if (!builder.CurrentParagraph.HasChildNodes)
builder.CurrentParagraph.Remove();
// Indicate to the mail merge engine that we have inserted what we wanted.
e.Text = null;
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document mainDoc = new Document(dataDir + "InsertDocument1.doc");
FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new InsertDocumentAtReplaceHandler();
mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"),"" , options);
dataDir = dataDir + "InsertDocumentAtReplace_out.doc";
mainDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
Document subDoc = new Document(RunExamples.GetDataDir_WorkingWithDocument() + "InsertDocument2.doc");
// Insert a document after the paragraph, containing the match text.
Paragraph para = (Paragraph)e.MatchNode.ParentNode;
InsertDocument(para, subDoc);
// Remove the paragraph with the match text.
para.Remove();
return ReplaceAction.Skip;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Inserts content of the external document after the specified node.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// Should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
static void InsertDocumentWithSectionFormatting(Node insertAfterNode, Document srcDoc)
{
// Make sure that the node is either a pargraph or table.
if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
(!insertAfterNode.NodeType.Equals(NodeType.Table)))
throw new ArgumentException("The destination node should be either a paragraph or table.");
// Document to insert srcDoc into.
Document dstDoc = (Document)insertAfterNode.Document;
// To retain section formatting, split the current section into two at the marker node and then import the content from srcDoc as whole sections.
// The section of the node which the insert marker node belongs to
Section currentSection = (Section)insertAfterNode.GetAncestor(NodeType.Section);
// Don't clone the content inside the section, we just want the properties of the section retained.
Section cloneSection = (Section)currentSection.Clone(false);
// However make sure the clone section has a body, but no empty first paragraph.
cloneSection.EnsureMinimum();
cloneSection.Body.FirstParagraph.Remove();
// Insert the cloned section into the document after the original section.
insertAfterNode.Document.InsertAfter(cloneSection, currentSection);
// Append all nodes after the marker node to the new section. This will split the content at the section level at
// The marker so the sections from the other document can be inserted directly.
Node currentNode = insertAfterNode.NextSibling;
while (currentNode != null)
{
Node nextNode = currentNode.NextSibling;
cloneSection.Body.AppendChild(currentNode);
currentNode = nextNode;
}
// This object will be translating styles and lists during the import.
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.UseDestinationStyles);
// Loop through all sections in the source document.
foreach (Section srcSection in srcDoc.Sections)
{
Node newNode = importer.ImportNode(srcSection, true);
// Append each section to the destination document. Start by inserting it after the split section.
dstDoc.InsertAfter(newNode, currentSection);
currentSection = (Section)newNode;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(inputFileName);
ProtectionType protectionType = doc.ProtectionType;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(inputFileName);
doc.Protect(ProtectionType.AllowOnlyFormFields, "password");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(inputFileName);
doc.Unprotect();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string fileName = "TestFile.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void RemovePageBreaks(Document doc)
{
// Retrieve all paragraphs in the document.
NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);
// Iterate through all paragraphs
foreach (Paragraph para in paragraphs)
{
// If the paragraph has a page break before set then clear it.
if (para.ParagraphFormat.PageBreakBefore)
para.ParagraphFormat.PageBreakBefore = false;
// Check all runs in the paragraph for page breaks and remove them.
foreach (Run run in para.Runs)
{
if (run.Text.Contains(ControlChar.PageBreak))
run.Text = run.Text.Replace(ControlChar.PageBreak, string.Empty);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void RemoveSectionBreaks(Document doc)
{
// Loop through all sections starting from the section that precedes the last one
// And moving to the first section.
for (int i = doc.Sections.Count - 2; i >= 0; i--)
{
// Copy the content of the current section to the beginning of the last section.
doc.LastSection.PrependContent(doc.Sections[i]);
// Remove the copied section.
doc.Sections[i].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_WorkingWithDocument();
Document doc = new Document(dataDir + "HeaderFooter.RemoveFooters.doc");
foreach (Section section in doc)
{
// Up to three different footers are possible in a section (for first, even and odd pages).
// We check and delete all of them.
HeaderFooter footer;
footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
if (footer != null)
footer.Remove();
// Primary footer is the footer used for odd pages.
footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
if (footer != null)
footer.Remove();
footer = section.HeadersFooters[HeaderFooterType.FooterEven];
if (footer != null)
footer.Remove();
}
dataDir = dataDir + "HeaderFooter.RemoveFooters_out.doc";
// Save the document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithStyles();
// Open a document which contains a TOC.
Document doc = new Document(dataDir + "Document.TableOfContents.doc");
// Remove the first table of contents from the document.
RemoveTableOfContents(doc, 0);
dataDir = dataDir + "Document.TableOfContentsRemoveToc_out.doc";
// Save the output.
doc.Save(dataDir);
Console.WriteLine("\nSpecified TOC from a document removed successfully.\nFile saved at " + dataDir);
}
/// <summary>
/// Removes the specified table of contents field from the document.
/// </summary>
/// <param name="doc">The document to remove the field from.</param>
/// <param name="index">The zero-based index of the TOC to remove.</param>
public static void RemoveTableOfContents(Document doc, int index)
{
// Store the FieldStart nodes of TOC fields in the document for quick access.
ArrayList fieldStarts = new ArrayList();
// This is a list to store the nodes found inside the specified TOC. They will be removed
// At the end of this method.
ArrayList nodeList = new ArrayList();
foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true))
{
if (start.FieldType == FieldType.FieldTOC)
{
// Add all FieldStarts which are of type FieldTOC.
fieldStarts.Add(start);
}
}
// Ensure the TOC specified by the passed index exists.
if (index > fieldStarts.Count - 1)
throw new ArgumentOutOfRangeException("TOC index is out of range");
bool isRemoving = true;
// Get the FieldStart of the specified TOC.
Node currentNode = (Node)fieldStarts[index];
while (isRemoving)
{
// It is safer to store these nodes and delete them all at once later.
nodeList.Add(currentNode);
currentNode = currentNode.NextPreOrder(doc);
// Once we encounter a FieldEnd node of type FieldTOC then we know we are at the end
// Of the current TOC and we can stop here.
if (currentNode.NodeType == NodeType.FieldEnd)
{
FieldEnd fieldEnd = (FieldEnd)currentNode;
if (fieldEnd.FieldType == FieldType.FieldTOC)
isRemoving = false;
}
}
// Remove all nodes found in the specified TOC.
foreach (Node node in nodeList)
{
node.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_WorkingWithDocument();
Document doc = new Document();
StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Block);
Paragraph para = new Paragraph(doc);
Run run = new Run(doc);
run.Text = "Hello World";
run.Font.Color = Color.Green;
para.Runs.Add(run);
sdtRichText.ChildNodes.Add(para);
doc.FirstSection.Body.AppendChild(sdtRichText);
dataDir = dataDir + "RichTextBoxContentControl_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(fileName);
doc.CompatibilityOptions.OptimizeFor(Settings.MsWordVersion.Word2016);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// 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.
LoadOptions loadOptions = new LoadOptions();
loadOptions.LanguagePreferences.AddEditingLanguage(EditingLanguage.Japanese);
Document doc = new Document(dataDir + @"languagepreferences.docx", loadOptions);
int localeIdFarEast = doc.Styles.DefaultFont.LocaleIdFarEast;
if (localeIdFarEast == (int)EditingLanguage.Japanese)
Console.WriteLine("The document either has no any FarEast language set in defaults or it was set to Japanese originally.");
else
Console.WriteLine("The document default FarEast language was set to another than Japanese language originally, so it is not overridden.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
LoadOptions loadOptions = new LoadOptions();
loadOptions.LanguagePreferences.SetAsDefault(EditingLanguage.Russian);
Document doc = new Document(dataDir + @"languagepreferences.docx", loadOptions);
int localeId = doc.Styles.DefaultFont.LocaleId;
if (localeId == (int)EditingLanguage.Russian)
Console.WriteLine("The document either has no any language set in defaults or it was set to Russian originally.");
else
Console.WriteLine("The document default language was set to another than Russian language originally, so it is not overridden.");
// 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_WorkingWithDocument();
// Load the template document.
Document doc = new Document(dataDir + "TestFile.doc");
// Set view option.
doc.ViewOptions.ViewType = ViewType.PageLayout;
doc.ViewOptions.ZoomPercent = 50;
dataDir = dataDir + "TestFile.SetZoom_out.doc";
// Save the finished document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open an existing document
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx");
foreach (StructuredDocumentTag sdt in doc.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
if (sdt.SdtType == SdtType.PlainText)
{
sdt.RemoveAllChildren();
Paragraph para = sdt.AppendChild(new Paragraph(doc)) as Paragraph;
Run run = new Run(doc, "new text goes here");
para.AppendChild(run);
}
else if (sdt.SdtType == SdtType.DropDownList)
{
SdtListItem secondItem = sdt.ListItems[2];
sdt.ListItems.SelectedValue = secondItem;
}
else if (sdt.SdtType == SdtType.Picture)
{
Shape shape = (Shape)sdt.GetChild(NodeType.Shape, 0, true);
if (shape.HasImage)
{
shape.ImageData.SetImage(dataDir + "Watermark.png");
}
}
}
dataDir = dataDir + "ModifyContentControls_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open an existing document
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get the first content control from the document
StructuredDocumentTag SdtCheckBox = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
// StructuredDocumentTag.Checked property gets/sets current state of the Checkbox SDT
if (SdtCheckBox.SdtType == SdtType.Checkbox)
SdtCheckBox.Checked = true;
dataDir = dataDir + "SetCurrentStateOfCheckBox_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 + "TestFile.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text");
builder.InsertFootnote(FootnoteType.Endnote, "Eootnote text.");
EndnoteOptions option = doc.EndnoteOptions;
option.RestartRule = FootnoteNumberingRule.RestartPage;
option.Position = EndnotePosition.EndOfSection;
dataDir = dataDir + "TestFile_Out.doc";
// 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
Document doc = new Document(dataDir + "TestFile.docx");
//Set footnote and endnode position.
doc.FootnoteOptions.Position = FootnotePosition.BeneathText;
doc.EndnoteOptions.Position = EndnotePosition.EndOfSection;
dataDir = dataDir + "TestFile_Out.doc";
// 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
Document doc = new Document(dataDir + "TestFile.docx");
//Specify the number of columns with which the footnotes area is formatted.
doc.FootnoteOptions.Columns = 3;
dataDir = dataDir + "TestFile_Out.doc";
// 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
Document doc = new Document(dataDir + "TestFile.docx");
//Set footnote and endnode position.
doc.FootnoteOptions.Position = FootnotePosition.BeneathText;
doc.EndnoteOptions.Position = EndnotePosition.EndOfSection;
dataDir = dataDir + "TestFile_Out.doc";
// 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
Document doc = new Document(dataDir + "Document.doc");
// Start tracking and make some revisions.
doc.StartTrackRevisions("Author");
doc.FirstSection.Body.AppendParagraph("Hello world!");
// Revisions will now show up as normal text in the output document.
doc.AcceptAllRevisions();
dataDir = dataDir + "Document.AcceptedRevisions_out.doc";
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 + "Revisions.docx");
foreach (RevisionGroup group in doc.Revisions.Groups)
{
Console.WriteLine("{0}, {1}:", group.Author, group.RevisionType);
Console.WriteLine(group.Text);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Revisions.docx");
ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;
for (int i = 0; i < paragraphs.Count; i++)
{
if (paragraphs[i].IsMoveFromRevision)
Console.WriteLine("The paragraph {0} has been moved (deleted).", i);
if (paragraphs[i].IsMoveToRevision)
Console.WriteLine("The paragraph {0} has been moved (inserted).", i);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Revisions.docx");
//Do not render the comments in PDF
doc.LayoutOptions.ShowComments = false;
doc.Save(dataDir + "RemoveCommentsinPDF_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Revisions.docx");
// Renders insert and delete revisions inline, format revisions in balloons.
doc.LayoutOptions.RevisionOptions.ShowInBalloons = ShowInBalloons.Format;
// Renders insert revisions inline, delete and format revisions in balloons.
//doc.LayoutOptions.RevisionOptions.ShowInBalloons = ShowInBalloons.FormatAndDelete;
doc.Save(dataDir + "SetShowInBalloons_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
//Load the Word document
Document doc = new Document(dataDir + @"Document.doc");
//Open Office uses centimeters when specifying lengths, widths and other measurable formatting
//and content properties in documents whereas MS Office uses inches.
OdtSaveOptions saveOptions = new OdtSaveOptions();
saveOptions.MeasureUnit = OdtSaveMeasureUnit.Inches;
//Save the document into ODT
doc.Save(dataDir + "MeasureUnit_out.odt", 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");
OoxmlSaveOptions options = new OoxmlSaveOptions();
options.UpdateLastSavedTimeProperty = true;
dataDir = dataDir + "UpdateLastSavedTimeProperty_out.docx";
// 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_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify font formatting before adding text.
Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;
builder.Write("Sample text.");
dataDir = dataDir + "WriteAndFont_out.doc";
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_WorkingWithFields();
// We will test this functionality creating a document with two fields with date formatting
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert content with German locale.
builder.Font.LocaleId = 1031;
builder.InsertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
builder.Write(" - ");
builder.InsertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");
// Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from.
// Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
doc.MailMerge.Execute(new string[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });
dataDir = dataDir + "Field.ChangeFieldUpdateCultureSource_out.doc";
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);
// Insert content with German locale.
builder.Font.LocaleId = 1031;
builder.InsertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
builder.Write(" - ");
builder.InsertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");
// 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_WorkingWithFields();
// Create a blank document.
Document doc = new Document();
DocumentBuilder b = new DocumentBuilder(doc);
b.InsertField("MERGEFIELD Date");
// Store the current culture so it can be set back once mail merge is complete.
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
// Set to German language so dates and numbers are formatted using this culture during mail merge.
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
// Execute mail merge.
doc.MailMerge.Execute(new string[] { "Date" }, new object[] { DateTime.Now });
// Restore the original culture.
Thread.CurrentThread.CurrentCulture = currentCulture;
doc.Save(dataDir + "Field.ChangeLocale_out.doc");
// 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_WorkingWithFields();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Pass the appropriate parameters to convert PAGE fields encountered to static text only in the body of the first section.
FieldsHelper.ConvertFieldsToStaticText(doc.FirstSection.Body, FieldType.FieldPage);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document with fields transformed 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_WorkingWithFields();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Pass the appropriate parameters to convert all IF fields encountered in the document (including headers and footers) to static text.
FieldsHelper.ConvertFieldsToStaticText(doc, FieldType.FieldIf);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document with fields transformed 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_WorkingWithFields();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Pass the appropriate parameters to convert all IF fields to static text that are encountered only in the last
// Paragraph of the document.
FieldsHelper.ConvertFieldsToStaticText(doc.FirstSection.Body.LastParagraph, FieldType.FieldIf);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document with fields transformed to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
DocumentBuilder builder = new DocumentBuilder();
FieldIf field = (FieldIf)builder.InsertField("IF 1 = 1", null);
FieldIfComparisonResult actualResult = field.EvaluateCondition();
Console.WriteLine(actualResult);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class FieldsHelper
{
/// <summary>
/// Converts any fields of the specified type found in the descendants of the node into static text.
/// </summary>
/// <param name="compositeNode">The node in which all descendants of the specified FieldType will be converted to static text.</param>
/// <param name="targetFieldType">The FieldType of the field to convert to static text.</param>
public static void ConvertFieldsToStaticText(CompositeNode compositeNode, FieldType targetFieldType)
{
compositeNode.Range.Fields.Cast<Field>().Where(f => f.Type == targetFieldType).ToList().ForEach(f => f.Unlink());
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
class FieldResultFormatter : IFieldResultFormatter
{
public FieldResultFormatter(string numberFormat, string dateFormat)
{
mNumberFormat = numberFormat;
mDateFormat = dateFormat;
}
public FieldResultFormatter()
: this(null, null)
{
}
public override string FormatNumeric(double value, string format)
{
mNumberFormatInvocations.Add(new object[] { value, format });
return string.IsNullOrEmpty(mNumberFormat)
? null
: string.Format(mNumberFormat, value);
}
public override string FormatDateTime(DateTime value, string format, CalendarType calendarType)
{
mDateFormatInvocations.Add(new object[] { value, format, calendarType });
return string.IsNullOrEmpty(mDateFormat)
? null
: string.Format(mDateFormat, value);
}
public override string Format(string value, GeneralFormat format)
{
throw new NotImplementedException();
}
public override string Format(double value, GeneralFormat format)
{
throw new NotImplementedException();
}
private readonly string mNumberFormat;
private readonly string mDateFormat;
private readonly ArrayList mNumberFormatInvocations = new ArrayList();
private readonly ArrayList mDateFormatInvocations = new ArrayList();
}
// 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_WorkingWithFields();
DocumentBuilder builder = new DocumentBuilder();
Document document = builder.Document;
Field field = builder.InsertField("=-1234567.89 \\# \"### ### ###.000\"", null);
document.FieldOptions.ResultFormatter = new FieldResultFormatter("[{0:N2}]", null);
field.Update();
dataDir = dataDir + "FormatFieldResult_out.docx";
builder.Document.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_WorkingWithFields();
Document doc = new Document(dataDir + "FormFields.doc");
FormFieldCollection documentFormFields = doc.Range.FormFields;
FormField formField1 = documentFormFields[3];
FormField formField2 = documentFormFields["Text2"];
// 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_WorkingWithFields();
Document doc = new Document(dataDir + "FormFields.doc");
FormFieldCollection formFields = doc.Range.FormFields;
// 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_WorkingWithFields();
Document doc = new Document(dataDir + "FormFields.doc");
FormField formField = doc.Range.FormFields[3];
if (formField.Type.Equals(FieldType.FieldFormTextInput))
formField.Result = "My name is " + formField.Name;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Shows how to delete all merge fields from a document without executing mail merge.
doc.MailMerge.DeleteFields();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Shows how to get names of all merge fields in a document.
string[] fieldNames = doc.MailMerge.GetFieldNames();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Shows how to add a mapping when a merge field in a document and a data field in a data source have different names.
doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource");
// 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_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this Advance field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an Advance field like this:
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
// Create instance of FieldAdvance class and lets build the above field code
FieldAdvance field = (FieldAdvance)para.AppendField(FieldType.FieldAdvance, false);
// { ADVANCE \\d 10 " }
field.DownOffset = "10";
// { ADVANCE \\d 10 \\l 10 }
field.LeftOffset = "10";
// { ADVANCE \\d 10 \\l 10 \\r -3.3 }
field.RightOffset = "-3.3";
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 }
field.UpOffset = "0";
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 }
field.HorizontalPosition = "100";
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
field.VerticalPosition = "100";
// Finally update this Advance field
field.Update();
dataDir = dataDir + "InsertAdvanceFieldWithOutDocumentBuilder_out.doc";
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_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this Ask field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an Ask field like this:
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
// Create instance of FieldAsk class and lets build the above field code
FieldAsk field = (FieldAsk)para.AppendField(FieldType.FieldAsk, false);
// { ASK \"Test 1\" " }
field.BookmarkName = "Test 1";
// { ASK \"Test 1\" Test2 }
field.PromptText = "Test2";
// { ASK \"Test 1\" Test2 \\d Test3 }
field.DefaultResponse = "Test3";
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
field.PromptOnceOnMailMerge = true;
// Finally update this Ask field
field.Update();
dataDir = dataDir + "InsertASKFieldWithOutDocumentBuilder_out.doc";
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_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this AUTHOR field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an AUTHOR field like this:
// { AUTHOR Test1 }
// Create instance of FieldAuthor class and lets build the above field code
FieldAuthor field = (FieldAuthor)para.AppendField(FieldType.FieldAuthor, false);
// { AUTHOR Test1 }
field.AuthorName = "Test1";
// Finally update this AUTHOR field
field.Update();
dataDir = dataDir + "InsertAuthorField_out.doc";
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_WorkingWithFields();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField(@"MERGEFIELD MyFieldName \* MERGEFORMAT");
dataDir = dataDir + "InsertField_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();
DocumentBuilder builder = new DocumentBuilder(doc);
FieldUnknown field = (FieldUnknown)builder.InsertField(FieldType.FieldNone, false);
dataDir = dataDir + "InsertFieldNone_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_WorkingWithFields();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
string[] items = { "One", "Two", "Three" };
builder.InsertComboBox("DropDown", items, 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_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this INCLUDETEXT field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an INCLUDETEXT field like this:
// { INCLUDETEXT "file path" }
// Create instance of FieldAsk class and lets build the above field code
FieldIncludeText fieldIncludeText = (FieldIncludeText)para.AppendField(FieldType.FieldIncludeText, false);
fieldIncludeText.BookmarkName = "bookmark";
fieldIncludeText.SourceFullName = dataDir + @"IncludeText.docx";
doc.FirstSection.Body.AppendChild(para);
// Finally update this IncludeText field
fieldIncludeText.Update();
dataDir = dataDir + "InsertIncludeFieldWithoutDocumentBuilder_out.doc";
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_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get paragraph you want to append this merge field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// Move cursor to this paragraph
builder.MoveTo(para);
// We want to insert a mail merge address block like this:
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
// Create instance of FieldAddressBlock class and lets build the above field code
FieldAddressBlock field = (FieldAddressBlock)builder.InsertField(FieldType.FieldAddressBlock, false);
// { ADDRESSBLOCK \\c 1" }
field.IncludeCountryOrRegionName = "1";
// { ADDRESSBLOCK \\c 1 \\d" }
field.FormatAddressOnCountryOrRegion = true;
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 }
field.ExcludedCountryOrRegionName = "Test2";
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 }
field.NameAndAddressFormat = "Test3";
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
field.LanguageId = "Test 4";
// Finally update this merge field
field.Update();
dataDir = dataDir + "InsertMailMergeAddressBlockFieldUsingDOM_out.doc";
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_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get paragraph you want to append this merge field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// Move cursor to this paragraph
builder.MoveTo(para);
// We want to insert a merge field like this:
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
// Create instance of FieldMergeField class and lets build the above field code
FieldMergeField field = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, false);
// { " MERGEFIELD Test1" }
field.FieldName = "Test1";
// { " MERGEFIELD Test1 \\b Test2" }
field.TextBefore = "Test2";
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 }
field.TextAfter = "Test3";
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m" }
field.IsMapped = true;
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
field.IsVerticalFormatting = true;
// Finally update this merge field
field.Update();
dataDir = dataDir + "InsertMergeFieldUsingDOM_out.doc";
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_WorkingWithFields();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a few page breaks (just for testing)
for (int i = 0; i < 5; i++)
builder.InsertBreak(BreakType.PageBreak);
// Move the DocumentBuilder cursor into the primary footer.
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
// We want to insert a field like this:
// { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" }
Field field = builder.InsertField(@"IF ");
builder.MoveTo(field.Separator);
builder.InsertField("PAGE");
builder.Write(" <> ");
builder.InsertField("NUMPAGES");
builder.Write(" \"See Next Page\" \"Last Page\" ");
// Finally update the outer field to recalcaluate the final value. Doing this will automatically update
// The inner fields at the same time.
field.Update();
dataDir = dataDir + "InsertNestedFields_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_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this TOA field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert TA and TOA fields like this:
// { TA \c 1 \l "Value 0" }
// { TOA \c 1 }
// Create instance of FieldAsk class and lets build the above field code
FieldTA fieldTA = (FieldTA)para.AppendField(FieldType.FieldTOAEntry, false);
fieldTA.EntryCategory = "1";
fieldTA.LongCitation = "Value 0";
doc.FirstSection.Body.AppendChild(para);
para = new Paragraph(doc);
// Create instance of FieldToa class
FieldToa fieldToa = (FieldToa)para.AppendField(FieldType.FieldTOA, false);
fieldToa.EntryCategory = "1";
doc.FirstSection.Body.AppendChild(para);
// Finally update this TOA field
fieldToa.Update();
dataDir = dataDir + "InsertTOAFieldWithoutDocumentBuilder_out.doc";
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_WorkingWithFields();
Document doc = new Document(dataDir + "Field.RemoveField.doc");
Field field = doc.Range.Fields[0];
// Calling this method completely removes the field from the document.
field.Remove();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Represents a facade object for a merge field in a Microsoft Word document.
/// </summary>
internal class MergeField
{
internal MergeField(FieldStart fieldStart)
{
if (fieldStart.Equals(null))
throw new ArgumentNullException("fieldStart");
if (!fieldStart.FieldType.Equals(FieldType.FieldMergeField))
throw new ArgumentException("Field start type must be FieldMergeField.");
mFieldStart = fieldStart;
// Find the field separator node.
mFieldSeparator = fieldStart.GetField().Separator;
if (mFieldSeparator == null)
throw new InvalidOperationException("Cannot find field separator.");
mFieldEnd = fieldStart.GetField().End;
}
/// <summary>
/// Gets or sets the name of the merge field.
/// </summary>
internal string Name
{
get
{
return ((FieldStart)mFieldStart).GetField().Result.Replace("«", "").Replace("»", "");
}
set
{
// Merge field name is stored in the field result which is a Run
// Node between field separator and field end.
Run fieldResult = (Run)mFieldSeparator.NextSibling;
fieldResult.Text = string.Format("«{0}»", value);
// But sometimes the field result can consist of more than one run, delete these runs.
RemoveSameParent(fieldResult.NextSibling, mFieldEnd);
UpdateFieldCode(value);
}
}
private void UpdateFieldCode(string fieldName)
{
// Field code is stored in a Run node between field start and field separator.
Run fieldCode = (Run)mFieldStart.NextSibling;
Match match = gRegex.Match(((FieldStart)mFieldStart).GetField().GetFieldCode());
string newFieldCode = string.Format(" {0}{1} ", match.Groups["start"].Value, fieldName);
fieldCode.Text = newFieldCode;
// But sometimes the field code can consist of more than one run, delete these runs.
RemoveSameParent(fieldCode.NextSibling, mFieldSeparator);
}
/// <summary>
/// Removes nodes from start up to but not including the end node.
/// Start and end are assumed to have the same parent.
/// </summary>
private static void RemoveSameParent(Node startNode, Node endNode)
{
if ((endNode != null) && ((Node)startNode.ParentNode != (Node)endNode.ParentNode))
throw new ArgumentException("Start and end nodes are expected to have the same parent.");
Node curChild = startNode;
while ((curChild != null) && (curChild != endNode))
{
Node nextChild = curChild.NextSibling;
curChild.Remove();
curChild = nextChild;
}
}
private readonly Node mFieldStart;
private readonly Node mFieldSeparator;
private readonly Node mFieldEnd;
private static readonly Regex gRegex = new Regex(@"\s*(?<start>MERGEFIELD\s|)(\s|)(?<name>\S+)\s+");
}
// 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_WorkingWithFields();
// Specify your document name here.
Document doc = new Document(dataDir + "RenameMergeFields.doc");
// Select all field start nodes so we can find the merge fields.
NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);
foreach (FieldStart fieldStart in fieldStarts)
{
if (fieldStart.FieldType.Equals(FieldType.FieldMergeField))
{
MergeField mergeField = new MergeField(fieldStart);
mergeField.Name = mergeField.Name + "_Renamed";
}
}
dataDir = dataDir + "RenameMergeFields_out.doc";
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_WorkingWithFields();
DocumentBuilder builder = new DocumentBuilder();
Field field = builder.InsertField(FieldType.FieldDate, true);
field.LocaleId = 1049;
builder.Document.Save(dataDir + "SpecifylocaleAtFieldlevel_out.docx");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment