Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active April 20, 2021 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save aspose-com-gists/0b968ac8900f80c11e109dffb105f3da to your computer and use it in GitHub Desktop.
Save aspose-com-gists/0b968ac8900f80c11e109dffb105f3da to your computer and use it in GitHub Desktop.
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
This Gist contains CSharp code snippets for examples of Aspose.Words for .NET.
using Aspose.Words;
using System;
namespace AsposeWordsDockerTest
{
class Program
{
static void Main(string[] args)
{
// Create document and save it in all available formats.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello from Aspose.Words!!!");
foreach (SaveFormat sf in Enum.GetValues(typeof(SaveFormat)))
{
if (sf != SaveFormat.Unknown)
{
try
{
doc.Save(string.Format("out{0}", FileFormatUtil.SaveFormatToExtension(sf)), sf);
Console.WriteLine("Saving {0}\t\t[OK]", sf);
}
catch
{
Console.WriteLine("Saving {0}\t\t[FAILED]", sf);
}
}
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "BubbleChart.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "template_cleanup.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
engine.Options = ReportBuildOptions.RemoveEmptyParagraphs;
engine.BuildReport(doc, Common.GetManagers(), "managers");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "BulletedList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetClients(), "clients");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class PointData
{
public string Time { get; set; }
public int Flow { get; set; }
public int Rainfall { get; set; }
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
List<PointData> data = new List<PointData>()
{
new PointData { Time = "12:00:00 AM", Flow = 10, Rainfall = 2 },
new PointData { Time = "01:00:00 AM", Flow = 15, Rainfall = 4 },
new PointData { Time = "02:00:00 AM", Flow = 23, Rainfall = 7 }
};
List<string> seriesNames = new List<string>
{
"Flow",
"Rainfall"
};
Document doc = new Document(dataDir + "ChartTemplate.docx");
ReportingEngine engine = new ReportingEngine();
engine.BuildReport(doc, new object[] { data, seriesNames }, new string[] { "data", "seriesNames" });
doc.Save(dataDir + "ChartTemplate_Out.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_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.docx");
// 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
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).docx");
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
// Open a Word document
Document doc = new Document(dataDir + "Test File (doc).docx");
HtmlSaveOptions options = new HtmlSaveOptions();
// Split a document into smaller parts, in this instance split by heading
options.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;
// Save the output file
doc.Save(dataDir + "SplitDocumentByHeadings_out.html", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
HtmlSaveOptions options = new HtmlSaveOptions();
options.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;
// 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).docx");
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
// Load the document from disk.
Document doc = new Document(dataDir + "Test.docx");
// Save the document to Markdown format.
doc.Save(dataDir + "SaveDocx2Markdown.md");
// 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.docx");
MarkdownSaveOptions so = new MarkdownSaveOptions();
so.ImagesFolder = dataDir + "\\Images";
using (MemoryStream stream = new MemoryStream())
doc.Save(stream, so);
// 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);
// Specify the "Heading 1" style for the paragraph.
builder.InsertParagraph();
builder.ParagraphFormat.StyleName = "Heading 1";
builder.Write("Heading 1");
// Specify the Italic emphasis for the paragraph.
builder.InsertParagraph();
// Reset styles from the previous paragraph to not combine styles between paragraphs.
builder.ParagraphFormat.StyleName = "Normal";
builder.Font.Italic = true;
builder.Write("Italic Text");
// Reset styles from the previous paragraph to not combine styles between paragraphs.
builder.Italic = false;
// Specify a Hyperlink for the desired text.
builder.InsertParagraph();
builder.InsertHyperlink("Aspose", "https://www.aspose.com", false);
builder.Write("Aspose");
// Save your document as a Markdown file.
doc.Save("example.md");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Words.
Document doc = new Document(dataDir + "Test File (docx).docx");
// Save into a memory stream in MHTML format.
Stream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Mhtml);
// Rewind the stream to the beginning so Aspose.Email can read it.
stream.Position = 0;
// Create an Aspose.Network MIME email message from the stream.
MailMessage message = MailMessage.Load(stream, new MhtmlLoadOptions());
message.From = "your_from@email.com";
message.To = "your_to@email.com";
message.Subject = "Aspose.Words + Aspose.Email MHTML Test Message";
// Send the message using Aspose.Email
SmtpClient client = new SmtpClient();
client.Host = "your_smtp.com";
client.Send(message);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (docx).docx");
PclSaveOptions saveOptions = new PclSaveOptions();
saveOptions.SaveFormat = SaveFormat.Pcl;
saveOptions.RasterizeTransformedElements = false;
// Export the document as an PCL file.
doc.Save(dataDir + "Document.PclConversion_out.pcl", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Initialize a Document.
Document doc = new Document();
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello World!");
dataDir = dataDir + "CreateDocument_out.docx";
// Save the document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// The path to the document which is to be processed.
string filePath = dataDir + "Document.Signed.docx";
FileFormatInfo info = FileFormatUtil.DetectFileFormat(filePath);
if (info.HasDigitalSignature)
{
Console.WriteLine("Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.", Path.GetFileName(filePath));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");
// Load the certificate from disk.
// The other constructor overloads can be used to load certificates from different locations.
X509Certificate2 cert = new X509Certificate2(
dataDir + "signature.pfx", "signature");
// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails();
dataDir = dataDir + "Document.Signed_out.pdf";
// Save the document as PDF.
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
using System.Security.Cryptography.X509Certificates;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(
CertificateHolder.Create(dataDir + "CioSrv1.pfx", "cinD96..arellA"),"reason","location",DateTime.Now);
doc.Save(dataDir + @"DigitallySignedPdfUsingCertificateHolder.Signed_out.pdf", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Load the document from disk.
Document doc = new Document(dataDir + "Rendering.doc");
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.DisplayDocTitle = true;
// Save the document in PDF format.
doc.Save(dataDir + "DisplayDocTitleInWindowTitlebar.pdf", 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 + "Rendering.docx");
// Save the document in PDF format.
doc.Save(dataDir + "SaveDoc2Pdf.pdf");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void PdfRenderWarnings(string dataDir)
{
// Load the document from disk.
Document doc = new Document(dataDir + "PdfRenderWarnings.doc");
// Set a SaveOptions object to not emulate raster operations.
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.MetafileRenderingOptions = new MetafileRenderingOptions
{
EmulateRasterOperations = false,
RenderingMode = MetafileRenderingMode.VectorWithFallback
};
// If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
HandleDocumentWarnings callback = new HandleDocumentWarnings();
doc.WarningCallback = callback;
doc.Save(dataDir + "PdfRenderWarnings.pdf", saveOptions);
// While the file saves successfully, rendering warnings that occurred during saving are collected here.
foreach (WarningInfo warningInfo in callback.mWarnings)
{
Console.WriteLine(warningInfo.Description);
}
}
public class HandleDocumentWarnings : IWarningCallback
{
/// <summary>
/// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
/// potential issue during document processing. The callback can be set to listen for warnings generated during document
/// load and/or document save.
/// </summary>
public void Warning(WarningInfo info)
{
//For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
if (info.WarningType == WarningType.MinorFormattingLoss)
{
Console.WriteLine("Unsupported operation: " + info.Description);
mWarnings.Warning(info);
}
}
public WarningInfoCollection mWarnings = new WarningInfoCollection();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class HandleDocumentWarnings : IWarningCallback
{
/// <summary>
/// Our callback only needs to implement the "Warning" method. This method is called whenever there is a
/// potential issue during document processing. The callback can be set to listen for warnings generated during document
/// load and/or document save.
/// </summary>
public void Warning(WarningInfo info)
{
//For now type of warnings about unsupported metafile records changed from DataLoss/UnexpectedContent to MinorFormattingLoss.
if (info.WarningType == WarningType.MinorFormattingLoss)
{
Console.WriteLine("Unsupported operation: " + info.Description);
mWarnings.Warning(info);
}
}
public WarningInfoCollection mWarnings = new WarningInfoCollection();
}
public static void RenderMetafileToBitmap(string dataDir)
{
// Load the document from disk.
Document doc = new Document(dataDir + "PdfRenderWarnings.doc");
MetafileRenderingOptions metafileRenderingOptions =
new MetafileRenderingOptions
{
EmulateRasterOperations = false,
RenderingMode = MetafileRenderingMode.VectorWithFallback
};
// If Aspose.Words cannot correctly render some of the metafile records to vector graphics then Aspose.Words renders this metafile to a bitmap.
HandleDocumentWarnings callback = new HandleDocumentWarnings();
doc.WarningCallback = callback;
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.MetafileRenderingOptions = metafileRenderingOptions;
doc.Save(dataDir + "PdfSaveOptions.HandleRasterWarnings.pdf", 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.docx";
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.docx";
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.ConvertMetafilesToPng = true;
Document doc = new Document(dataDir + "in.doc", lo);
// 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
public class DocumentLoadingWarningCallback : IWarningCallback
{
public void Warning(WarningInfo info)
{
// Prints warnings and their details as they arise during document loading.
Console.WriteLine($"WARNING: {info.WarningType}, source: {info.Source}");
Console.WriteLine($"\tDescription: {info.Description}");
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class HtmlLinkedResourceLoadingCallback : IResourceLoadingCallback
{
public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
{
switch (args.ResourceType)
{
case ResourceType.CssStyleSheet:
{
Console.WriteLine($"External CSS Stylesheet found upon loading: {args.OriginalUri}");
// CSS file will don't used in the document
return ResourceLoadingAction.Skip;
}
case ResourceType.Image:
{
// Replaces all images with a substitute
const string newImageFilename = "Logo.jpg";
Console.WriteLine($"\tImage will be substituted with: {newImageFilename}");
Image newImage = Image.FromFile(RunExamples.GetDataDir_QuickStart() + newImageFilename);
ImageConverter converter = new ImageConverter();
byte[] imageBytes = (byte[])converter.ConvertTo(newImage, typeof(byte[]));
args.SetData(imageBytes);
// New images will be used instead of presented in the document
return ResourceLoadingAction.UserProvided;
}
case ResourceType.Document:
{
Console.WriteLine($"External document found upon loading: {args.OriginalUri}");
// Will be used as usual
return ResourceLoadingAction.Default;
}
default:
throw new InvalidOperationException("Unexpected ResourceType value.");
}
}
}
// 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
// Set the Encoding attribute in a LoadOptions object to override the automatically chosen encoding with the one we know to be correct
LoadOptions loadOptions = new LoadOptions { Encoding = Encoding.UTF7 };
Document doc = new Document(dataDir + "Encoded in UTF-7.txt", loadOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Create a new LoadOptions object and set its ResourceLoadingCallback attribute as an instance of our IResourceLoadingCallback implementation
LoadOptions loadOptions = new LoadOptions { ResourceLoadingCallback = new HtmlLinkedResourceLoadingCallback() };
// When we open an Html document, external resources such as references to CSS stylesheet files and external images
// will be handled in a custom manner by the loading callback as the document is loaded
Document doc = new Document(dataDir + "Images.html", loadOptions);
doc.Save(dataDir + "Document.LoadOptionsCallback_out.pdf");
// 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
// Create a new LoadOptions object and set its WarningCallback property.
LoadOptions loadOptions = new LoadOptions { WarningCallback = new DocumentLoadingWarningCallback() };
Document doc = new Document(dataDir + "document.docx", loadOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Create a new LoadOptions object, which will load documents according to MS Word 2019 specification by default.
LoadOptions loadOptions = new LoadOptions();
// Change the loading version to Microsoft Word 2010.
loadOptions.MswVersion = MsWordVersion.Word2010;
Document doc = new Document(dataDir + "document.docx", loadOptions);
doc.Save(dataDir + "Word2003_out.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
LoadOptions lo = new LoadOptions();
lo.TempFolder = @"C:\TempFolder\";
Document doc = new Document(dataDir + "document.docx", lo);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
PdfLoadOptions loadOptions = new PdfLoadOptions();
loadOptions.SkipPdfImages = true;
Document doc = new Document(dataDir + "in.pdf", loadOptions);
// 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.Docx);
// 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 + "', @Docx)";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Add the @Docx parameter.
command.Parameters.AddWithValue("Docx", 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.docx";
// 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.docx";
// 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.docx";
// 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.docx";
// Open the stream. Read only access is enough for Aspose.Words to load a document.
Stream stream = File.OpenRead(dataDir + fileName);
// Load the entire document into memory.
Document doc = new Document(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// The encoding of the text file is automatically detected.
Document doc = new Document(dataDir + "LoadTxt.txt");
// Save as any Aspose.Words supported format, such as DOCX.
dataDir = dataDir + "LoadTxt_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Loads encrypted document.
Document doc = new Document(dataDir + "LoadEncrypted.docx", new LoadOptions("aspose"));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Document.doc");
dataDir = dataDir + "Document.ConvertToTxt_out.txt";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Here is an SVG image: ");
builder.InsertHtml(
@"<svg height='210' width='500'>
<polygon points='100,10 40,198 190,78 10,78 160,198'
style='fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;' />
</svg> ");
HtmlSaveOptions options = new HtmlSaveOptions();
options.MetafileFormat = HtmlMetafileFormat.Svg;
dataDir = dataDir + "ExportSVGinHTML_out.html";
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.docx");
HtmlSaveOptions options = new HtmlSaveOptions();
options.MetafileFormat = HtmlMetafileFormat.EmfOrWmf;
dataDir = dataDir + "SaveHtmlWithMetafileFormat_out.html";
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.docx");
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.CssStyleSheetType = CssStyleSheetType.External;
saveOptions.CssClassNamePrefix = "pfx_";
dataDir = dataDir + "CssClassNamePrefix_out.html";
doc.Save(dataDir, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
var doc = new Aspose.Words.Document(dataDir + "CidUrls.docx");
Aspose.Words.Saving.HtmlSaveOptions saveOptions = new Aspose.Words.Saving.HtmlSaveOptions(SaveFormat.Mhtml);
saveOptions.PrettyFormat = true;
saveOptions.ExportCidUrlsForMhtmlResources = true;
saveOptions.SaveFormat = SaveFormat.Mhtml;
dataDir = dataDir + "SetExportCidUrlsForMhtmlResources_out.mhtml";
doc.Save(dataDir, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Test File (docx).docx");
Aspose.Words.Saving.HtmlSaveOptions saveOptions = new Aspose.Words.Saving.HtmlSaveOptions(SaveFormat.Html);
saveOptions.PrettyFormat = true;
saveOptions.ResolveFontNames = true;
dataDir = dataDir + "ResolveFontNames_out.html";
doc.Save(dataDir, saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlFixedSaveOptions options = new HtmlFixedSaveOptions();
options.UseTargetMachineFonts = true;
dataDir = dataDir + "UseFontFromTargetMachine_out.html";
// Save the document to disk.
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlFixedSaveOptions options = new HtmlFixedSaveOptions();
//Setting this property to true restores the old behavior (separate files) for compatibility with legacy code.
//Default value is false.
//All CSS rules are written into single file "styles.css
options.SaveFontFaceCssSeparately = false;
dataDir = dataDir + "WriteAllCSSrulesinSingleFile_out.html";
// Save the document to disk.
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Document.docx");
dataDir = dataDir + "Report_out.docx";
// 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
DocumentBuilder builder = new DocumentBuilder();
// Create a new table with two cells.
builder.InsertCell();
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Write("Cell1");
builder.InsertCell();
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Write("Cell2");
MarkdownSaveOptions saveOptions = new MarkdownSaveOptions();
// Makes all paragraphs inside table to be aligned to Left.
saveOptions.TableContentAlignment = TableContentAlignment.Left;
builder.Document.Save(dataDir + "left.md", saveOptions);
// Makes all paragraphs inside table to be aligned to Right.
saveOptions.TableContentAlignment = TableContentAlignment.Right;
builder.Document.Save(dataDir + "right.md", saveOptions);
// Makes all paragraphs inside table to be aligned to Center.
saveOptions.TableContentAlignment = TableContentAlignment.Center;
builder.Document.Save(dataDir + "center.md", saveOptions);
// Makes all paragraphs inside table to be aligned automatically.
// The alignment in this case will be taken from the first paragraph in corresponding table column.
saveOptions.TableContentAlignment = TableContentAlignment.Auto;
builder.Document.Save(dataDir + "auto.md", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
DocumentBuilder builder = new DocumentBuilder();
builder.Writeln("Some text!");
// specify MarkDownSaveOptions
MarkdownSaveOptions saveOptions = (MarkdownSaveOptions)SaveOptions.CreateSaveOptions(SaveFormat.Markdown);
builder.Document.Save(dataDir + "TestDocument.md", 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 = "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
Document doc = new Document(dataDir + "Document.doc");
DocSaveOptions saveOptions = new DocSaveOptions();
saveOptions.AlwaysCompressMetafiles = false;
doc.Save(dataDir + "SmallMetafilesUncompressed.doc", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.docx");
DocSaveOptions docSaveOptions = new DocSaveOptions();
docSaveOptions.Password = "password";
dataDir = dataDir + "Document.Password_out.docx";
doc.Save(dataDir, docSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "in.doc");
DocSaveOptions saveOptions = (DocSaveOptions)SaveOptions.CreateSaveOptions(SaveFormat.Doc);
saveOptions.SavePictureBullet = false;
doc.Save(dataDir + "out.doc", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions();
ooxmlSaveOptions.Password = "password";
dataDir = dataDir + "Document.Password_out.docx";
doc.Save(dataDir, ooxmlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.FlatOpc);
so.KeepLegacyControlChars = true;
dataDir = dataDir + "Document_out.docx";
// Save the document to disk.
doc.Save(dataDir, so);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.Docx);
so.CompressionLevel = CompressionLevel.SuperFast;
// Save the document to disk.
doc.Save(dataDir + "SetCompressionLevel_out.docx", so);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.doc");
// Set Word2016 version for document
doc.CompatibilityOptions.OptimizeFor(MsWordVersion.Word2016);
//Set the Strict compliance level.
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions
{
Compliance = OoxmlCompliance.Iso29500_2008_Strict,
SaveFormat = SaveFormat.Docx
};
dataDir = dataDir + "Document.Iso29500_2008_Strict_out.docx";
doc.Save(dataDir, ooxmlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.docx");
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions();
ooxmlSaveOptions.UpdateLastSavedTimeProperty = true;
dataDir = dataDir + "UpdateLastSavedTimeProperty_out.docx";
// Save the document to disk.
doc.Save(dataDir, ooxmlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
RtfLoadOptions loadOptions = new RtfLoadOptions();
loadOptions.RecognizeUtf8Text = true;
Document doc = new Document(dataDir + "Utf8Text.rtf", loadOptions);
dataDir = dataDir + "RecognizeUtf8Text_out.rtf";
doc.Save(dataDir);
// 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 = true;
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
Document doc1 = new Document("input_document");
doc1.Save(dataDir + "output1.txt");
Document doc2 = new Document("input_document");
TxtSaveOptions options = new TxtSaveOptions();
doc2.Save(dataDir + "output2.txt", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
TxtLoadOptions loadOptions = new TxtLoadOptions();
loadOptions.DetectNumberingWithWhitespaces = false;
Document doc = new Document(dataDir + "LoadTxt.txt", loadOptions);
dataDir = dataDir + "DetectNumberingWithWhitespaces_out.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
TxtLoadOptions loadOptions = new TxtLoadOptions();
loadOptions.DocumentDirection = DocumentDirection.Auto;
Document doc = new Document(dataDir + "arabic.txt", loadOptions);
Paragraph paragraph = doc.FirstSection.Body.FirstParagraph;
Console.WriteLine(paragraph.ParagraphFormat.Bidi);
dataDir = dataDir + "DocumentDirection_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
Document doc = new Document("input_document");
TxtSaveOptions options = new TxtSaveOptions();
options.ListIndentation.Count = 3;
options.ListIndentation.Character = ' ';
doc.Save(dataDir + "output.txt", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document("input_document");
TxtSaveOptions options = new TxtSaveOptions();
options.ListIndentation.Count = 1;
options.ListIndentation.Character = '\t';
doc.Save(dataDir + "output.txt", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "VbaProject_source.docm");
VbaProject project = doc.VbaProject;
Document destDoc = new Document();
destDoc.VbaProject = new VbaProject();
// Clone a single module.
VbaModule copyModule = doc.VbaProject.Modules["Module1"].Clone();
destDoc.VbaProject.Modules.Add(copyModule);
destDoc.Save(dataDir + "output.docm");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "VbaProject_source.docm");
VbaProject project = doc.VbaProject;
Document destDoc = new Document();
// Clone the whole project.
destDoc.VbaProject = doc.VbaProject.Clone();
destDoc.Save(dataDir + "output.docm");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Create a new VBA project.
VbaProject project = new VbaProject();
project.Name = "AsposeProject";
doc.VbaProject = project;
// Create a new module and specify a macro source code.
VbaModule module = new VbaModule();
module.Name = "AsposeModule";
module.Type = VbaModuleType.ProceduralModule;
module.SourceCode = "New source code";
// Add module to the VBA project.
doc.VbaProject.Modules.Add(module);
doc.Save(dataDir + "VbaProject_out.docm");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "test.docm");
VbaProject project = doc.VbaProject;
const string newSourceCode = "Test change source code";
// Choose a module, and set a new source code.
project.Modules[0].SourceCode = newSourceCode;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Document.dot");
if (doc.VbaProject != null)
{
foreach (VbaModule module in doc.VbaProject.Modules)
{
Console.WriteLine(module.SourceCode);
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Returns string representing LibId path of a specified reference.
/// </summary>
private static string GetLibIdPath(VbaReference reference)
{
switch (reference.Type)
{
case VbaReferenceType.Registered:
case VbaReferenceType.Original:
case VbaReferenceType.Control:
return GetLibIdReferencePath(reference.LibId);
case VbaReferenceType.Project:
return GetLibIdProjectPath(reference.LibId);
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Returns path from a specified identifier of an Automation type library.
/// </summary>
/// <remarks>
/// Please see details for the syntax at [MS-OVBA], 2.1.1.8 LibidReference.
/// </remarks>
private static string GetLibIdReferencePath(string libIdReference)
{
if (libIdReference != null)
{
string[] refParts = libIdReference.Split('#');
if (refParts.Length > 3)
return refParts[3];
}
return "";
}
/// <summary>
/// Returns path from a specified identifier of an Automation type library.
/// </summary>
/// <remarks>
/// Please see details for the syntax at [MS-OVBA], 2.1.1.12 ProjectReference.
/// </remarks>
private static string GetLibIdProjectPath(string libIdProject)
{
return (libIdProject != null) ? libIdProject.Substring(3) : "";
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "VbaProject.docm");
// Find and remove the reference with some LibId path.
const string brokenPath = "brokenPath.dll";
VbaReferenceCollection references = doc.VbaProject.References;
for (int i = references.Count - 1; i >= 0; i--)
{
VbaReference reference = doc.VbaProject.References.ElementAt(i);
string path = GetLibIdPath(reference);
if (path == brokenPath)
references.RemoveAt(i);
}
doc.Save(dataDir + "NoBrokenRef.docm");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
LoadOptions options = new LoadOptions
{
Encoding = Encoding.GetEncoding("windows-1251")
};
Document doc = new Document(dataDir + "help.chm", 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_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);
// Use DataTable as a data source.
int orderId = 10444;
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";
// Execute the mail merge operation.
doc.MailMerge.ExecuteWithRegions(orderDetailsView);
// Save the merged document.
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
Document doc = new Document(dataDir + "RemoveRowfromTable.docx");
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields;
doc.MailMerge.Execute(new string[] { "FullName", "Company", "Address", "Address2", "City" },
new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
doc.Save(dataDir + "MailMerge.ExecuteArray_out.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "RemoveRowfromTable.docx");
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
doc.MailMerge.Execute(new string[] { "FullName", "Company", "Address", "Address2", "City" },
new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
doc.Save(dataDir + "MailMerge.ExecuteArray_out.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "RemoveRowfromTable.docx");
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyTableRows;
doc.MailMerge.Execute(new string[] { "FullName", "Company", "Address", "Address2", "City" },
new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
doc.Save(dataDir + "MailMerge.ExecuteArray_out.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "RemoveRowfromTable.docx");
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedFields;
doc.MailMerge.Execute(new string[] { "FullName", "Company", "Address", "Address2", "City" },
new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
doc.Save(dataDir + "MailMerge.ExecuteArray_out.doc");
// 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)
{
args.ImageFileName = "Image.png";
args.ImageWidth.Value = 200;
args.ImageHeight = new MergeFieldImageDimension(200, MergeFieldImageDimensionUnit.Percent);
}
private DocumentBuilder mBuilder;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
args.ImageFileName = "Image.png";
args.ImageWidth.Value = 200;
args.ImageHeight = new MergeFieldImageDimension(200, MergeFieldImageDimensionUnit.Percent);
}
// 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 DataSourceRoot : IMailMergeDataSourceRoot
{
public IMailMergeDataSource GetDataSource(String s)
{
return new DataSource();
}
private class DataSource : IMailMergeDataSource
{
bool next = true;
string IMailMergeDataSource.TableName => TableName();
public string TableName()
{
return "example";
}
public bool MoveNext()
{
bool result = next;
next = false;
return result;
}
public IMailMergeDataSource GetChildDataSource(String s)
{
return null;
}
public bool GetValue(string fieldName, out object fieldValue)
{
fieldValue = null;
return false;
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class ImageFieldMergingHandler : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
// Implementation is not required.
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
Shape shape = new Shape(args.Document, ShapeType.Image);
shape.Width = 126;
shape.Height = 126;
shape.WrapType = WrapType.Square;
string imageFileName = Path.GetFullPath(RunExamples.GetDataDir_WorkingWithDocument() + "image.png");
shape.ImageData.SetImage(imageFileName);
args.Shape = shape;
}
}
// 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 + "template.docx");
doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.TrimWhitespaces = true;
doc.MailMerge.UseWholeParagraphAsRegion = false;
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyTableRows
| MailMergeCleanupOptions.RemoveContainingFields
| MailMergeCleanupOptions.RemoveUnusedRegions
| MailMergeCleanupOptions.RemoveUnusedFields;
// Add a handler for the MergeField event.
doc.MailMerge.FieldMergingCallback = new ImageFieldMergingHandler();
doc.MailMerge.ExecuteWithRegions(new DataSourceRoot());
dataDir = dataDir + "MailMerge.ImageMailMerge_out.doc";
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
public Document CreateMailMergeTemplate()
{
DocumentBuilder builder = new DocumentBuilder();
// Insert a text input field the unique name of this field is "Hello", the other parameters define
// what type of FormField it is, the format of the text, the field result and the maximum text length (0 = no limit)
builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", "Hello", 0);
builder.InsertField(@"MERGEFIELD CustomerFirstName \* MERGEFORMAT");
builder.InsertTextInput("TextInput1", TextFormFieldType.Regular, "", " ", 0);
builder.InsertField(@"MERGEFIELD CustomerLastName \* MERGEFORMAT");
builder.InsertTextInput("TextInput1", TextFormFieldType.Regular, "", " , ", 0);
// Inserts a paragraph break into the document
builder.InsertParagraph();
// Insert mail body
builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", "Thanks for purchasing our ", 0);
builder.InsertField(@"MERGEFIELD ProductName \* MERGEFORMAT");
builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", ", please download your Invoice at ",
0);
builder.InsertField(@"MERGEFIELD InvoiceURL \* MERGEFORMAT");
builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "",
". If you have any questions please call ", 0);
builder.InsertField(@"MERGEFIELD Supportphone \* MERGEFORMAT");
builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", ", or email us at ", 0);
builder.InsertField(@"MERGEFIELD SupportEmail \* MERGEFORMAT");
builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", ".", 0);
builder.InsertParagraph();
// Insert mail ending
builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", "Best regards,", 0);
builder.InsertBreak(BreakType.LineBreak);
builder.InsertField(@"MERGEFIELD EmployeeFullname \* MERGEFORMAT");
builder.InsertTextInput("TextInput1", TextFormFieldType.Regular, "", " ", 0);
builder.InsertField(@"MERGEFIELD EmployeeDepartment \* MERGEFORMAT");
return builder.Document;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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
// Load a document
Document doc = new Document(dataDir + @"Test.docx");
// Loop through each row and fill it with data
DataTable dataTable = new DataTable("list");
dataTable.Columns.Add("Number");
for (int i = 0; i < 10; i++)
{
DataRow datarow = dataTable.NewRow();
dataTable.Rows.Add(datarow);
datarow[0] = "Number " + i;
}
// Activate performing a mail merge operation into additional field types
doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.ExecuteWithRegions(dataTable);
doc.Save(dataDir + "MailMerge.Mustache.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open a template document.
Document doc = new Document(dataDir + "UseOfifelseMustacheSyntax.docx");
doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.Execute(new String[] { "GENDER" }, new Object[] { "MALE" });
dataDir = dataDir + "MailMergeUsingMustacheSyntaxifelse_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
private static DataSet CreateDataSet()
{
// Create the customers table.
DataTable tableCustomers = new DataTable("Customers");
tableCustomers.Columns.Add("CustomerID");
tableCustomers.Columns.Add("CustomerName");
tableCustomers.Rows.Add(new object[] { 1, "John Doe" });
tableCustomers.Rows.Add(new object[] { 2, "Jane Doe" });
// Create the orders table.
DataTable tableOrders = new DataTable("Orders");
tableOrders.Columns.Add("CustomerID");
tableOrders.Columns.Add("ItemName");
tableOrders.Columns.Add("Quantity");
tableOrders.Rows.Add(new object[] { 1, "Hawaiian", 2 });
tableOrders.Rows.Add(new object[] { 2, "Pepperoni", 1 });
tableOrders.Rows.Add(new object[] { 2, "Chicago", 1 });
// Add both tables to a data set.
DataSet dataSet = new DataSet();
dataSet.Tables.Add(tableCustomers);
dataSet.Tables.Add(tableOrders);
// The "CustomerID" column, also the primary key of the customers table is the foreign key for the Orders table.
dataSet.Relations.Add(tableCustomers.Columns["CustomerID"], tableOrders.Columns["CustomerID"]);
return dataSet;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Mail merge regions.docx");
IList<MailMergeRegionInfo> regions = doc.MailMerge.GetRegionsByName("Region1");
Assert.AreEqual(1, doc.MailMerge.GetRegionsByName("Region1").Count);
foreach (MailMergeRegionInfo region in regions) Assert.AreEqual("Region1", region.Name);
regions = doc.MailMerge.GetRegionsByName("Region2");
Assert.AreEqual(1, doc.MailMerge.GetRegionsByName("Region2").Count);
foreach (MailMergeRegionInfo region in regions) Assert.AreEqual("Region2", region.Name);
regions = doc.MailMerge.GetRegionsByName("NestedRegion1");
Assert.AreEqual(2, doc.MailMerge.GetRegionsByName("NestedRegion1").Count);
foreach (MailMergeRegionInfo region in regions) Assert.AreEqual("NestedRegion1", region.Name);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public void MailMergeWithRegions()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// The start point of mail merge with regions the dataset.
builder.InsertField(" MERGEFIELD TableStart:Customers");
// Data from rows of the "CustomerName" column of the "Customers" table will go in this MERGEFIELD.
builder.Write("Orders for ");
builder.InsertField(" MERGEFIELD CustomerName");
builder.Write(":");
// Create column headers
builder.StartTable();
builder.InsertCell();
builder.Write("Item");
builder.InsertCell();
builder.Write("Quantity");
builder.EndRow();
// We have a second data table called "Orders", which has a many-to-one relationship with "Customers"
// picking up rows with the same CustomerID value.
builder.InsertCell();
builder.InsertField(" MERGEFIELD TableStart:Orders");
builder.InsertField(" MERGEFIELD ItemName");
builder.InsertCell();
builder.InsertField(" MERGEFIELD Quantity");
builder.InsertField(" MERGEFIELD TableEnd:Orders");
builder.EndTable();
// The end point of mail merge with regions.
builder.InsertField(" MERGEFIELD TableEnd:Customers");
// Pass our dataset to perform mail merge with regions.
DataSet customersAndOrders = CreateDataSet();
doc.MailMerge.ExecuteWithRegions(customersAndOrders);
// Save the result
doc.Save("Your local path to save the document" + "MailMerge.ExecuteWithRegions.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_MailMergeAndReporting();
// Create the Dataset and read the XML.
DataSet pizzaDs = new DataSet();
// The Datatable.TableNames and the DataSet.Relations are defined implicitly by .NET through ReadXml.
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);
Debug.Assert(doc.MailMerge.GetFieldNames().Length == 0, "There was a problem with mail merge");
Console.WriteLine("\nMail merge performed with nested data successfully.\nFile saved at " + 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
//Put the path to the documents directory and open the template:
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
Document doc = new Document(dataDir + "TestFile.doc");
// 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);
//Perform a loop through each DataRow to iterate through the DataTable.
//Clone the template document instead of loading it from disk for better speed performance before the mail merge operation.
//You can load the template document from a file or stream but it is faster to load the document only once and then clone it in memory before each mail merge operation.
int counter = 1;
foreach (DataRow row in data.Rows)
{
Document dstDoc = (Document) doc.Clone(true);
dstDoc.MailMerge.Execute(row);
dstDoc.Save(string.Format(dataDir + "TestFile_out{0}.doc", counter++));
}
Console.WriteLine("\nProduce multiple documents performed successfully.\nFile saved at " + dataDir);
// 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
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
const string fileName = "TestFile Empty.doc";
Document doc = new Document(dataDir + fileName);
// Create an empty data source in the form of a DataSet containing no DataTable objects.
DataSet data = new DataSet();
// Enable the MailMergeCleanupOptions.RemoveUnusedRegions option.
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions;
// Merge the data with the document by executing 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
public static void SimpleMailMergeExecuteArray()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Include the code for our template.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Create Merge Fields.
builder.InsertField(" MERGEFIELD CustomerName ");
builder.InsertParagraph();
builder.InsertField(" MERGEFIELD Item ");
builder.InsertParagraph();
builder.InsertField(" MERGEFIELD Quantity ");
builder.Document.Save(dataDir + "MailMerge.TestTemplate.docx");
// Fill the fields in the document with user data.
doc.MailMerge.Execute(new string[] { "CustomerName", "Item", "Quantity" },
new object[] { "John Doe", "Hawaiian", "2" });
builder.Document.Save(dataDir + "MailMerge.Simple.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_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
// 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
// Create empty document
Document doc = new Document(dataDir + "Bookmark.Table_out.doc");
foreach (Bookmark bookmark in doc.Range.Bookmarks)
{
Console.WriteLine("Bookmark: {0}{1}", bookmark.Name, bookmark.IsColumn ? " (Column)" : "");
if (bookmark.IsColumn)
{
Row row = bookmark.BookmarkStart.GetAncestor(NodeType.Row) as Row;
if (row != null && bookmark.FirstColumn < row.Cells.Count)
Console.WriteLine(row.Cells[bookmark.FirstColumn].GetText().TrimEnd(ControlChar.CellChar));
}
}
// 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
public static void ShowHideBookmarkedContent(Document doc, String bookmarkName, bool showHide)
{
DocumentBuilder builder = new DocumentBuilder(doc);
Bookmark bm = doc.Range.Bookmarks[bookmarkName];
builder.MoveToDocumentEnd();
// {IF "{MERGEFIELD bookmark}" = "true" "" ""}
Field field = builder.InsertField("IF \"", null);
builder.MoveTo(field.Start.NextSibling);
builder.InsertField("MERGEFIELD " + bookmarkName + "", null);
builder.Write("\" = \"true\" ");
builder.Write("\"");
builder.Write("\"");
builder.Write(" \"\"");
Node currentNode = field.Start;
bool flag = true;
while (currentNode != null && flag)
{
if (currentNode.NodeType == NodeType.Run)
if (currentNode.ToString(SaveFormat.Text).Trim().Equals("\""))
flag = false;
Node nextNode = currentNode.NextSibling;
bm.BookmarkStart.ParentNode.InsertBefore(currentNode, bm.BookmarkStart);
currentNode = nextNode;
}
Node endNode = bm.BookmarkEnd;
flag = true;
while (currentNode != null && flag)
{
if (currentNode.NodeType == NodeType.FieldEnd)
flag = false;
Node nextNode = currentNode.NextSibling;
bm.BookmarkEnd.ParentNode.InsertAfter(currentNode, endNode);
endNode = currentNode;
currentNode = nextNode;
}
doc.MailMerge.Execute(new String[] { bookmarkName }, new Object[] { showHide });
//MailMerge can be avoided by using the following
//builder.MoveToMergeField(bookmarkName);
//builder.Write(showHide ? "true" : "false");
}
// 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");
ShowHideBookmarkedContent(doc, "Bookmark2", false);
doc.Save(dataDir + "Updated_Document.doc");
// 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 series1 = chart.Series.Add("AW Series 1",
new string[] { "AW0", "AW1", "AW2" },
new double[] { 2.5, 1.5, 3.5 });
series1.HasDataLabels = true;
series1.DataLabels.ShowValue = true;
series1.DataLabels[0].NumberFormat.FormatCode = "\"$\"#,##0.00";
series1.DataLabels[1].NumberFormat.FormatCode = "dd/mm/yyyy";
series1.DataLabels[2].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.
series1.DataLabels[2].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
Document doc = new Document(dataDir + "Document.docx");
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
ChartAxis axis = shape.Chart.AxisX;
//This property has effect only for multi-line labels.
axis.TickLabelAlignment = ParagraphAlignment.Right;
doc.Save(dataDir + "Document_out.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_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
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertChart(ChartType.Pie, 432, 252);
Chart chart = shape.Chart;
chart.Series.Clear();
ChartSeries series = chart.Series.Add("Series 1",
new string[] { "Category1", "Category2", "Category3" },
new double[] { 2.7, 3.2, 0.8 });
ChartDataLabelCollection labels = series.DataLabels;
labels.ShowPercentage = true;
labels.ShowValue = true;
labels.ShowLeaderLines = false;
labels.Separator = " - ";
doc.Save(dataDir + "Demo.docx");
// 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);
Shape shape = builder.InsertChart(ChartType.Bar, 432, 252);
Chart chart = shape.Chart;
// Get first series.
ChartSeries series0 = shape.Chart.Series[0];
ChartDataLabelCollection labels = series0.DataLabels;
// Set properties.
labels.ShowLegendKey = true;
// By default, when you add data labels to the data points in a pie chart, leader lines are displayed for data labels that are
// Positioned far outside the end of data points. Leader lines create a visual connection between a data label and its
// Corresponding data point.
labels.ShowLeaderLines = true;
labels.ShowCategoryName = false;
labels.ShowPercentage = false;
labels.ShowSeriesName = true;
labels.ShowValue = true;
labels.Separator = "/";
labels.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();
// Initialize document.
Document doc = new Document(dataDir + "Document.doc");
RunCollection runs = doc.FirstSection.Body.FirstParagraph.Runs;
Font runFont = runs[0].Font;
// One run might have several Dml text effects applied.
Console.WriteLine(runFont.HasDmlEffect(TextDmlEffect.Shadow));
Console.WriteLine(runFont.HasDmlEffect(TextDmlEffect.Effect3D));
Console.WriteLine(runFont.HasDmlEffect(TextDmlEffect.Reflection));
Console.WriteLine(runFont.HasDmlEffect(TextDmlEffect.Outline));
Console.WriteLine(runFont.HasDmlEffect(TextDmlEffect.Fill));
// 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();
// If either marker is part of a comment then to include the comment itself we need to move the pointer
// forward to the Comment Node found after the CommentRangeEnd node.
if (endNode.NodeType == NodeType.CommentRangeEnd && isInclusive)
{
Node node = FindNextNode(NodeType.Comment, endNode.NextSibling);
if (node != null)
endNode = node;
}
// 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
startNode = GetAncestorInBody(startNode);
endNode = GetAncestorInBody(endNode);
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)
{
// We need to process each marker separately so pass it off to a separate method instead.
// End should be processed at first to keep node indexes.
if (isEndingNode)
{
// !isStartingNode: don't add the node twice if the markers are the same node.
ProcessMarker(cloneNode, nodes, originalEndNode, currNode, isInclusive,
false, !isStartingNode, false);
isExtracting = false;
}
// Conditional needs to be separate as the block level start and end markers maybe the same node.
if (isStartingNode)
{
ProcessMarker(cloneNode, nodes, originalStartNode, currNode, isInclusive,
true, true, false);
isStartingNode = false;
}
}
else
// 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;
}
}
// For compatibility with mode with inline bookmarks, add the next paragraph (empty).
if (isInclusive && originalEndNode == endNode && !originalEndNode.IsComposite)
IncludeNextParagraph(endNode, nodes);
// 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(GetAncestorInBody(startNode)) >
endSection.Body.IndexOf(GetAncestorInBody(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 Node FindNextNode(NodeType nodeType, Node fromNode)
{
if (fromNode == null || fromNode.NodeType == nodeType)
return fromNode;
if (fromNode.IsComposite)
{
Node node = FindNextNode(nodeType, ((CompositeNode)fromNode).FirstChild);
if (node != null)
return node;
}
return FindNextNode(nodeType, fromNode.NextSibling);
}
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(Node cloneNode, ArrayList nodes, Node node, Node blockLevelAncestor,
bool isInclusive, bool isStartMarker, bool canAdd, bool forceAdd)
{
// If we are dealing with a block level node just see if it should be included and add it to the list.
if (node == blockLevelAncestor)
{
if (canAdd && isInclusive)
nodes.Add(cloneNode);
return;
}
// cloneNode is a clone of blockLevelNode. If node != blockLevelNode, blockLevelAncestor is ancestor of node
// that means it is a composite node.
System.Diagnostics.Debug.Assert(cloneNode.IsComposite);
// If a marker is a FieldStart node check if it's to be included or not.
// We assume for simplicity that the FieldStart and FieldEnd appear in the same paragraph.
if (node.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;
}
}
// Support a case if marker node is on the third level of document body or lower.
List<Node> nodeBranch = FillSelfAndParents(node, blockLevelAncestor);
// Process the corresponding node in our cloned node by index.
Node currentCloneNode = cloneNode;
for (int i = nodeBranch.Count - 1; i >= 0; i--)
{
Node currentNode = nodeBranch[i];
int nodeIndex = currentNode.ParentNode.IndexOf(currentNode);
currentCloneNode = ((CompositeNode)currentCloneNode).ChildNodes[nodeIndex];
RemoveNodesOutsideOfRange(currentCloneNode, isInclusive || (i > 0), isStartMarker);
}
// After processing the composite node may become empty. If it has don't include it.
if (canAdd &&
(forceAdd || ((CompositeNode)cloneNode).HasChildNodes))
nodes.Add(cloneNode);
}
private static void RemoveNodesOutsideOfRange(Node markerNode, bool isInclusive, bool isStartMarker)
{
// Remove the nodes up to/from the marker.
bool isSkip = false;
bool isProcessing = true;
bool isRemoving = isStartMarker;
Node nextNode = markerNode.ParentNode.FirstChild;
while (isProcessing && nextNode != null)
{
Node currentNode = nextNode;
isSkip = false;
if (currentNode.Equals(markerNode))
{
if (isStartMarker)
{
isProcessing = false;
if (isInclusive)
isRemoving = false;
}
else
{
isRemoving = true;
if (isInclusive)
isSkip = true;
}
}
nextNode = nextNode.NextSibling;
if (isRemoving && !isSkip)
currentNode.Remove();
}
}
private static List<Node> FillSelfAndParents(Node node, Node tillNode)
{
List<Node> list = new List<Node>();
Node currentNode = node;
while (currentNode != tillNode)
{
list.Add(currentNode);
currentNode = currentNode.ParentNode;
}
return list;
}
private static void IncludeNextParagraph(Node node, ArrayList nodes)
{
Paragraph paragraph = (Paragraph)FindNextNode(NodeType.Paragraph, node.NextSibling);
if (paragraph != null)
{
// Move to first child to include paragraph without contents.
Node markerNode = paragraph.HasChildNodes ? paragraph.FirstChild : paragraph;
Node rootNode = GetAncestorInBody(paragraph);
ProcessMarker(rootNode.Clone(true), nodes, markerNode, rootNode,
markerNode == paragraph, false, true, true);
}
}
private static Node GetAncestorInBody(Node startNode)
{
while (startNode.ParentNode.NodeType != NodeType.Body)
startNode = startNode.ParentNode;
return startNode;
}
// 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
DocumentBuilder builderA = new DocumentBuilder(new Document());
DocumentBuilder builderB = new DocumentBuilder(new Document());
builderA.Writeln("This is A simple word");
builderB.Writeln("This is B simple words");
CompareOptions co = new CompareOptions();
co.Granularity = Granularity.CharLevel;
builderA.Document.Compare(builderB.Document, "author", DateTime.Now, co);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "Properties.doc";
Document document = new Document(dataDir + fileName);
var collector = new LayoutCollector(document);
var it = new LayoutEnumerator(document);
foreach (Paragraph paragraph in document.GetChildNodes(NodeType.Paragraph, true))
{
var paraBreak = collector.GetEntity(paragraph);
object stop = null;
var prevItem = paragraph.PreviousSibling;
if (prevItem != null)
{
var prevBreak = collector.GetEntity(prevItem);
if (prevItem is Paragraph)
{
it.Current = collector.GetEntity(prevItem); // para break
it.MoveParent(); // last line
stop = it.Current;
}
else if (prevItem is Table)
{
var table = (Table)prevItem;
it.Current = collector.GetEntity(table.LastRow.LastCell.LastParagraph); // cell break
it.MoveParent(); // cell
it.MoveParent(); // row
stop = it.Current;
}
else
{
throw new Exception();
}
}
it.Current = paraBreak;
it.MoveParent();
// We move from line to line in a paragraph.
// When paragraph spans multiple pages the we will follow across them.
var count = 1;
while (it.Current != stop)
{
if (!it.MovePreviousLogical())
break;
count++;
}
const int MAX_CHARS = 16;
var paraText = paragraph.GetText();
if (paraText.Length > MAX_CHARS)
paraText = $"{paraText.Substring(0, MAX_CHARS)}...";
Console.WriteLine($"Paragraph '{paraText}' has {count} line(-s).");
}
// 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 + "test.docx");
// Retrieve a list of all custom document properties from the file.
CustomDocumentProperties customProperties = doc.CustomDocumentProperties;
// Add linked to content property.
DocumentProperty customProperty = customProperties.AddLinkToContent("PropertyName", "BookmarkName");
// Also, accessing the custom document property can be performed by using the property name.
customProperty = customProperties["PropertyName"];
// Check whether the property is linked to content.
bool isLinkedToContent = customProperty.IsLinkToContent;
// Get the source of the property.
string source = customProperty.LinkSource;
// Get the value of the property.
string value = customProperty.Value.ToString();
// 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
DocumentBuilder builder = new DocumentBuilder();
Shape shape = builder.InsertHorizontalRule();
HorizontalRuleFormat horizontalRuleFormat = shape.HorizontalRuleFormat;
horizontalRuleFormat.Alignment = HorizontalRuleAlignment.Center;
horizontalRuleFormat.WidthPercent = 70;
horizontalRuleFormat.Height = 3;
horizontalRuleFormat.Color = Color.Blue;
horizontalRuleFormat.NoShade = true;
builder.Document.Save("HorizontalRuleFormat.docx");
// 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
// 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
// Load document with OLE object.
Document doc = new Document(dataDir + "DocumentBuilderInsertTextInputFormField_out.doc");
Shape oleShape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
byte[] oleRawData = oleShape.OleFormat.GetRawData();
// 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(dataDir + "Input.docx");
ParagraphFormat format = doc.FirstSection.Body.FirstParagraph.ParagraphFormat;
format.CharacterUnitLeftIndent = 10; // ParagraphFormat.LeftIndent will be updated
format.CharacterUnitRightIndent = 10; // ParagraphFormat.RightIndent will be updated
format.CharacterUnitFirstLineIndent = 20; // ParagraphFormat.FirstLineIndent will be updated
format.LineUnitBefore = 5; // ParagraphFormat.SpaceBefore will be updated
format.LineUnitAfter = 10; // ParagraphFormat.SpaceAfter will be updated
dataDir = dataDir + "ChangeAsianParagraphSpacingandIndents_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 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
Document document = new Document();
DocumentBuilder builder = new DocumentBuilder(document);
builder.Font.EmphasisMark = EmphasisMark.UnderSolidCircle;
builder.Write("Emphasis text");
builder.Writeln();
builder.Font.ClearFormatting();
builder.Write("Simple text");
document.Save(dataDir + "FontEmphasisMark_out.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir);
Paragraph par = doc.FirstSection.Body.FirstParagraph;
par.ParagraphFormat.SnapToGrid = true;
par.Runs[0].Font.SnapToGrid = true;
dataDir = dataDir + "SetSnapToGrid_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();
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment