Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aspose-words/55f18a258ff768b6c366 to your computer and use it in GitHub Desktop.

Select an option

Save aspose-words/55f18a258ff768b6c366 to your computer and use it in GitHub Desktop.
This Gist contains code snippets for sample code of Aspose.Words
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
// For complete examples and 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 = "BulletedList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetClients(), "clients");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "ChartWithFilteringGroupingOrdering.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class Client
{
public String Name { get; set; }
}
// 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" }, Manager = manager, Price = 1200000, Date = new DateTime(2015, 1, 1) },
new Contract { Client = new Client { Name = "B Ltd." }, Manager = manager, Price = 750000, Date = new DateTime(2015, 4, 1) },
new Contract { Client = new Client { Name = "C & D" }, 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." }, Manager = manager, Price = 650000, Date = new DateTime(2015, 2, 1) },
new Contract { Client = new Client { Name = "F & Partners" }, 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." }, Manager = manager, Price = 350000, Date = new DateTime(2015, 2, 1) },
new Contract { Client = new Client { Name = "H Group" }, Manager = manager, Price = 250000, Date = new DateTime(2015, 5, 1) },
new Contract { Client = new Client { Name = "I & Sons" }, Manager = manager, Price = 100000, Date = new DateTime(2015, 7, 1) },
new Contract { Client = new Client { Name = "J Ent." }, 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
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
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LINQ();
string fileName = "SingleRow.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Load the photo and read all bytes.
byte[] imgdata = System.IO.File.ReadAllBytes(dataDir + "photo.png");
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.BuildReport(doc, Common.GetManager(), "manager");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Test File (doc).doc");
foreach (DigitalSignature signature in doc.DigitalSignatures)
{
Console.WriteLine("*** Signature Found ***");
Console.WriteLine("Is valid: " + signature.IsValid);
Console.WriteLine("Reason for signing: " + signature.Comments); // This property is available in MS Word documents only.
Console.WriteLine("Time of signing: " + signature.SignTime);
Console.WriteLine("Subject name: " + signature.CertificateHolder.Certificate.SubjectName.Name);
Console.WriteLine("Issuer name: " + signature.CertificateHolder.Certificate.IssuerName.Name);
Console.WriteLine();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string supportedDir = dataDir + "OutSupported";
string unknownDir = dataDir + "OutUnknown";
string encryptedDir = dataDir + "OutEncrypted";
string pre97Dir = dataDir + "OutPre97";
// Create the directories if they do not already exist
if (Directory.Exists(supportedDir) == false)
Directory.CreateDirectory(supportedDir);
if (Directory.Exists(unknownDir) == false)
Directory.CreateDirectory(unknownDir);
if (Directory.Exists(encryptedDir) == false)
Directory.CreateDirectory(encryptedDir);
if (Directory.Exists(pre97Dir) == false)
Directory.CreateDirectory(pre97Dir);
string[] fileList = Directory.GetFiles(dataDir);
// Loop through all found files.
foreach (string fileName in fileList)
{
// Extract and display the file name without the path.
string nameOnly = Path.GetFileName(fileName);
Console.Write(nameOnly);
// Check the file format and move the file to the appropriate folder.
FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);
// Display the document type.
switch (info.LoadFormat)
{
case LoadFormat.Doc:
Console.WriteLine("\tMicrosoft Word 97-2003 document.");
break;
case LoadFormat.Dot:
Console.WriteLine("\tMicrosoft Word 97-2003 template.");
break;
case LoadFormat.Docx:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document.");
break;
case LoadFormat.Docm:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
break;
case LoadFormat.Dotx:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template.");
break;
case LoadFormat.Dotm:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
break;
case LoadFormat.FlatOpc:
Console.WriteLine("\tFlat OPC document.");
break;
case LoadFormat.Rtf:
Console.WriteLine("\tRTF format.");
break;
case LoadFormat.WordML:
Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
break;
case LoadFormat.Html:
Console.WriteLine("\tHTML format.");
break;
case LoadFormat.Mhtml:
Console.WriteLine("\tMHTML (Web archive) format.");
break;
case LoadFormat.Odt:
Console.WriteLine("\tOpenDocument Text.");
break;
case LoadFormat.Ott:
Console.WriteLine("\tOpenDocument Text Template.");
break;
case LoadFormat.DocPreWord60:
Console.WriteLine("\tMS Word 6 or Word 95 format.");
break;
case LoadFormat.Unknown:
default:
Console.WriteLine("\tUnknown format.");
break;
}
// Now copy the document into the appropriate folder.
if (info.IsEncrypted)
{
Console.WriteLine("\tAn encrypted document.");
File.Copy(fileName, Path.Combine(encryptedDir, nameOnly), true);
}
else
{
switch (info.LoadFormat)
{
case LoadFormat.DocPreWord60:
File.Copy(fileName, Path.Combine(pre97Dir, nameOnly), true);
break;
case LoadFormat.Unknown:
File.Copy(fileName, Path.Combine(unknownDir, nameOnly), true);
break;
default:
File.Copy(fileName, Path.Combine(supportedDir, nameOnly), true);
break;
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Check the file format and move the file to the appropriate folder.
FileFormatInfo info = FileFormatUtil.DetectFileFormat(fileName);
// Display the document type.
switch (info.LoadFormat)
{
case LoadFormat.Doc:
Console.WriteLine("\tMicrosoft Word 97-2003 document.");
break;
case LoadFormat.Dot:
Console.WriteLine("\tMicrosoft Word 97-2003 template.");
break;
case LoadFormat.Docx:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Document.");
break;
case LoadFormat.Docm:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
break;
case LoadFormat.Dotx:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Free Template.");
break;
case LoadFormat.Dotm:
Console.WriteLine("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
break;
case LoadFormat.FlatOpc:
Console.WriteLine("\tFlat OPC document.");
break;
case LoadFormat.Rtf:
Console.WriteLine("\tRTF format.");
break;
case LoadFormat.WordML:
Console.WriteLine("\tMicrosoft Word 2003 WordprocessingML format.");
break;
case LoadFormat.Html:
Console.WriteLine("\tHTML format.");
break;
case LoadFormat.Mhtml:
Console.WriteLine("\tMHTML (Web archive) format.");
break;
case LoadFormat.Odt:
Console.WriteLine("\tOpenDocument Text.");
break;
case LoadFormat.Ott:
Console.WriteLine("\tOpenDocument Text Template.");
break;
case LoadFormat.DocPreWord60:
Console.WriteLine("\tMS Word 6 or Word 95 format.");
break;
case LoadFormat.Unknown:
default:
Console.WriteLine("\tUnknown format.");
break;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string[] fileList = Directory.GetFiles(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
// Create a new memory stream.
MemoryStream outStream = new MemoryStream();
// Save the document to stream.
doc.Save(outStream, SaveFormat.Docx);
// Convert the document to byte form.
byte[] docBytes = outStream.ToArray();
// The bytes are now ready to be stored/transmitted.
// Now reverse the steps to load the bytes back into a document object.
MemoryStream inStream = new MemoryStream(docBytes);
// Load the stream into a new document object.
Document loadDoc = new Document(inStream);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions =
new HtmlSaveOptions();
// Specify the desired encoding.
saveOptions.Encoding = System.Text.Encoding.UTF8;
// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph;
// Specify that we want to export document properties.
saveOptions.ExportDocumentProperties = true;
// Specify that we want to save in EPUB format.
saveOptions.SaveFormat = SaveFormat.Epub;
// Export the document as an EPUB file.
doc.Save(dataDir + "Document.EpubConversion_out_.epub", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void ConvertDocumentToEPUBUsingDefaultSaveOption()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Save the document in EPUB format.
doc.Save(dataDir + "Document.EpubConversionUsingDefaultSaveOption_out_.epub");
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlSaveOptions options = new HtmlSaveOptions();
//HtmlSaveOptions.ExportRoundtripInformation property specifies
//whether to write the roundtrip information when saving to HTML, MHTML or EPUB.
//Default value is true for HTML and false for MHTML and EPUB.
options.ExportRoundtripInformation = true;
doc.Save(dataDir + "ExportRoundtripInformation_out_.html", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Initialize a Document.
Document doc = new Document();
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello World!");
dataDir = dataDir + "CreateDocument_out_.docx";
// Save the document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// The path to the document which is to be processed.
string filePath = dataDir + "Document.Signed.docx";
FileFormatInfo info = FileFormatUtil.DetectFileFormat(filePath);
if (info.HasDigitalSignature)
{
Console.WriteLine(string.Format("Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.", Path.GetFileName(filePath)));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Create a simple document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Test Signed PDF.");
// Load the certificate from disk.
// The other constructor overloads can be used to load certificates from different locations.
X509Certificate2 cert = new X509Certificate2(
dataDir + "signature.pfx", "signature");
// Pass the certificate and details to the save options class to sign with.
PdfSaveOptions options = new PdfSaveOptions();
options.DigitalSignatureDetails = new PdfDigitalSignatureDetails();
dataDir = dataDir + "Document.Signed_out_.pdf";
// Save the document as PDF.
doc.Save(dataDir);
// 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_QuickStart();
// Load the document from disk.
Document doc = new Document(dataDir + "Template.doc");
dataDir = dataDir + "Template_out_.pdf";
// Save the document in PDF format.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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
public static void DeleteFromDatabase(string fileName, OleDbConnection mConnection)
{
// Create the SQL command.
string commandString = "DELETE * FROM Documents WHERE FileName='" + fileName + "'";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Delete the record.
command.ExecuteNonQuery();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string dbName = "";
// Open a database connection.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + RunExamples.GetDataDir_Database() + dbName;
OleDbConnection mConnection = new OleDbConnection(connString);
mConnection.Open();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Store the document to the database.
StoreToDatabase(doc, mConnection);
// Read the document from the database and store the file to disk.
Document dbDoc = ReadFromDatabase(fileName, mConnection);
// Save the retrieved document to disk.
string newFileName = Path.GetFileNameWithoutExtension(fileName) + " from DB" + Path.GetExtension(fileName);
dbDoc.Save(dataDir + newFileName);
// Delete the document from the database.
DeleteFromDatabase(fileName, mConnection);
// Close the connection to the database.
mConnection.Close();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static Document ReadFromDatabase(string fileName, OleDbConnection mConnection)
{
// Create the SQL command.
string commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Create the data adapter.
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
// Fill the results from the database into a DataTable.
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
// Check there was a matching record found from the database and throw an exception if no record was found.
if (dataTable.Rows.Count == 0)
throw new ArgumentException(string.Format("Could not find any record matching the document \"{0}\" in the database.", fileName));
// The document is stored in byte form in the FileContent column.
// Retrieve these bytes of the first matching record to a new buffer.
byte[] buffer = (byte[])dataTable.Rows[0]["FileContent"];
// Wrap the bytes from the buffer into a new MemoryStream object.
MemoryStream newStream = new MemoryStream(buffer);
// Read the document from the stream.
Document doc = new Document(newStream);
// Return the retrieved document.
return doc;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void StoreToDatabase(Document doc, OleDbConnection mConnection)
{
// Save the document to a MemoryStream object.
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Doc);
// Get the filename from the document.
string fileName = Path.GetFileName(doc.OriginalFileName);
// Create the SQL command.
string commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + fileName + "', @Doc)";
OleDbCommand command = new OleDbCommand(commandString, mConnection);
// Add the @Doc parameter.
command.Parameters.AddWithValue("Doc", stream.ToArray());
// Write the document to the database.
command.ExecuteNonQuery();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
string fileName = "Document.doc";
// Load the document from the absolute path on disk.
Document doc = new Document(dataDir + fileName);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document as DOCX document.");
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
string fileName = "Document.doc";
// Load the document from the absolute path on disk.
Document doc = new Document(dataDir + fileName);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
string fileName = "Document.doc";
// Open the stream. Read only access is enough for Aspose.Words to load a document.
Stream stream = File.OpenRead(dataDir + fileName);
// Load the entire document into memory.
Document doc = new Document(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();
// ... do something with the document
// Convert the document to a different format and save to stream.
MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Rtf);
// Rewind the stream position back to zero so it is ready for the next reader.
dstStream.Position = 0;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_QuickStart();
string fileName = "Document.doc";
// Open the stream. Read only access is enough for Aspose.Words to load a document.
Stream stream = File.OpenRead(dataDir + fileName);
// Load the entire document into memory.
Document doc = new Document(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// The encoding of the text file is automatically detected.
Document doc = new Document(dataDir + "LoadTxt.txt");
// Save as any Aspose.Words supported format, such as DOCX.
dataDir = dataDir + "LoadTxt_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
//Loads encrypted document.
Document doc = new Document(dataDir + "LoadEncrypted.docx", new LoadOptions("aspose"));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Document.doc");
dataDir = dataDir + "Document.ConvertToTxt_out_.txt";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
Document doc = new Document(dataDir + "Document.doc");
dataDir = dataDir + "Report_out.doc";
// If this method overload is causing a compiler error then you are using the Client Profile DLL whereas
// the Aspose.Words .NET 2.0 DLL must be used instead.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = "TestFile RenderShape.docx";
Document doc = new Document(dataDir + fileName);
// This is the directory we want the exported images to be saved to.
string imagesDir = Path.Combine(dataDir, "Images");
// The folder specified needs to exist and should be empty.
if (Directory.Exists(imagesDir))
Directory.Delete(imagesDir, true);
Directory.CreateDirectory(imagesDir);
// Set an option to export form fields as plain text, not as HTML input elements.
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
options.ExportTextInputFormFieldAsText = true;
options.ImagesFolder = imagesDir;
dataDir = dataDir + "Document.SaveWithOptions_out_.html";
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
string fileName = "TestFile.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// Create a data source which has some data missing.
// This will result in some regions that are merged and some that remain after executing mail merge.
DataSet data = GetDataSource();
// Make sure that we have not set the removal of any unused regions as we will handle them manually.
// We achieve this by removing the RemoveUnusedRegions flag from the cleanup options by using the AND and NOT bitwise operators.
doc.MailMerge.CleanupOptions = doc.MailMerge.CleanupOptions & ~MailMergeCleanupOptions.RemoveUnusedRegions;
// Execute mail merge. Some regions will be merged with data, others left unmerged.
doc.MailMerge.ExecuteWithRegions(data);
// The regions which contained data now would of been merged. Any regions which had no data and were
// not merged will still remain in the document.
Document mergedDoc = doc.Clone(); //ExSkip
// Apply logic to each unused region left in the document using the logic set out in the handler.
// The handler class must implement the IFieldMergingCallback interface.
ExecuteCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler());
// Save the output document to disk.
doc.Save(dataDir + "TestFile.CustomLogicEmptyRegions1_out_.doc");
// Reload the original merged document.
doc = mergedDoc.Clone();
// Apply different logic to unused regions this time.
ExecuteCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler_MergeTable());
doc.Save(dataDir + "TestFile.CustomLogicEmptyRegions2_out_.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Only handle the ContactDetails region in our handler.
ArrayList regions = new ArrayList();
regions.Add("ContactDetails");
ExecuteCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler(), regions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
dataSet.Relations.Add(new DataRelation("OrderToItem", orderTable.Columns["Order_Id"], itemTable.Columns["Order_Id"]));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Returns a DataSet object containing a DataTable for the unmerged regions in the specified document.
/// If regionsList is null all regions found within the document are included. If an ArrayList instance is present
/// the only the regions specified in the list that are found in the document are added.
/// </summary>
private static DataSet CreateDataSourceFromDocumentRegions(Document doc, ArrayList regionsList)
{
const string tableStartMarker = "TableStart:";
DataSet dataSet = new DataSet();
string tableName = null;
foreach (string fieldName in doc.MailMerge.GetFieldNames())
{
if (fieldName.Contains(tableStartMarker))
{
tableName = fieldName.Substring(tableStartMarker.Length);
}
else if (tableName != null)
{
// Only add the table name as a new DataTable if it doesn't already exists in the DataSet.
if (dataSet.Tables[tableName] == null)
{
DataTable table = new DataTable(tableName);
table.Columns.Add(fieldName);
// We only need to add the first field for the handler to be called for the fields in the region.
if (regionsList == null || regionsList.Contains(tableName))
{
table.Rows.Add("FirstField");
}
dataSet.Tables.Add(table);
}
tableName = null;
}
}
return dataSet;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
dataSet.Relations.Add(new DataRelation("OrderToItem", orderTable.Columns["Order_Id"], itemTable.Columns["Order_Id"], false));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class EmptyRegionsHandler : IFieldMergingCallback
{
/// <summary>
/// Called for each field belonging to an unmerged region in the document.
/// </summary>
public void FieldMerging(FieldMergingArgs args)
{
// Change the text of each field of the ContactDetails region individually.
if (args.TableName == "ContactDetails")
{
// Set the text of the field based off the field name.
if (args.FieldName == "Name")
args.Text = "(No details found)";
else if (args.FieldName == "Number")
args.Text = "(N/A)";
}
// Remove the entire table of the Suppliers region. Also check if the previous paragraph
// before the table is a heading paragraph and if so remove that too.
if (args.TableName == "Suppliers")
{
Table table = (Table)args.Field.Start.GetAncestor(NodeType.Table);
// Check if the table has been removed from the document already.
if (table.ParentNode != null)
{
// Try to find the paragraph which precedes the table before the table is removed from the document.
if (table.PreviousSibling != null && table.PreviousSibling.NodeType == NodeType.Paragraph)
{
Paragraph previousPara = (Paragraph)table.PreviousSibling;
if (IsHeadingParagraph(previousPara))
previousPara.Remove();
}
table.Remove();
}
}
}
/// <summary>
/// Returns true if the paragraph uses any Heading style e.g Heading 1 to Heading 9
/// </summary>
private bool IsHeadingParagraph(Paragraph para)
{
return (para.ParagraphFormat.StyleIdentifier >= StyleIdentifier.Heading1 && para.ParagraphFormat.StyleIdentifier <= StyleIdentifier.Heading9);
}
public void ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do Nothing
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Applies logic defined in the passed handler class to all unused regions in the document. This allows to manually control
/// how unused regions are handled in the document.
/// </summary>
/// <param name="doc">The document containing unused regions</param>
/// <param name="handler">The handler which implements the IFieldMergingCallback interface and defines the logic to be applied to each unmerged region.</param>
public static void ExecuteCustomLogicOnEmptyRegions(Document doc, IFieldMergingCallback handler)
{
ExecuteCustomLogicOnEmptyRegions(doc, handler, null); // Pass null to handle all regions found in the document.
}
/// <summary>
/// Applies logic defined in the passed handler class to specific unused regions in the document as defined in regionsList. This allows to manually control
/// how unused regions are handled in the document.
/// </summary>
/// <param name="doc">The document containing unused regions</param>
/// <param name="handler">The handler which implements the IFieldMergingCallback interface and defines the logic to be applied to each unmerged region.</param>
/// <param name="regionsList">A list of strings corresponding to the region names that are to be handled by the supplied handler class. Other regions encountered will not be handled and are removed automatically.</param>
public static void ExecuteCustomLogicOnEmptyRegions(Document doc, IFieldMergingCallback handler, ArrayList regionsList)
{
// Certain regions can be skipped from applying logic to by not adding the table name inside the CreateEmptyDataSource method.
// Enable this cleanup option so any regions which are not handled by the user's logic are removed automatically.
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions;
// Set the user's handler which is called for each unmerged region.
doc.MailMerge.FieldMergingCallback = handler;
// Execute mail merge using the dummy dataset. The dummy data source contains the table names of
// each unmerged region in the document (excluding ones that the user may have specified to be skipped). This will allow the handler
// to be called for each field in the unmerged regions.
doc.MailMerge.ExecuteWithRegions(CreateDataSourceFromDocumentRegions(doc, regionsList));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Replace the unused region in the table with a "no records" message and merge all cells into one.
if (args.TableName == "Suppliers")
{
if ((string)args.FieldValue == "FirstField")
{
// We will use the first paragraph to display our message. Make it centered within the table. The other fields in other cells
// within the table will be merged and won't be displayed so we don't need to do anything else with them.
parentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Center;
args.Text = "No records to display";
}
// Merge the cells of the table together.
Cell cell = (Cell)parentParagraph.GetAncestor(NodeType.Cell);
if (cell != null)
{
if (cell.IsFirstCell)
cell.CellFormat.HorizontalMerge = CellMerge.First; // If this cell is the first cell in the table then the merge is started using "CellMerge.First".
else
cell.CellFormat.HorizontalMerge = CellMerge.Previous; // Otherwise the merge is continued using "CellMerge.Previous".
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Store the parent paragraph of the current field for easy access.
Paragraph parentParagraph = args.Field.Start.ParentParagraph;
// Define the logic to be used when the ContactDetails region is encountered.
// The region is removed and replaced with a single line of text stating that there are no records.
if (args.TableName == "ContactDetails")
{
// Called for the first field encountered in a region. This can be used to execute logic on the first field
// in the region without needing to hard code the field name. Often the base logic is applied to the first field and
// different logic for other fields. The rest of the fields in the region will have a null FieldValue.
if ((string)args.FieldValue == "FirstField")
{
FindReplaceOptions options = new FindReplaceOptions();
// Remove the "Name:" tag from the start of the paragraph
parentParagraph.Range.Replace("Name:", string.Empty, options);
// Set the text of the first field to display a message stating that there are no records.
args.Text = "No records to display";
}
else
{
// We have already inserted our message in the paragraph belonging to the first field. The other paragraphs in the region
// will still remain so we want to remove these. A check is added to ensure that the paragraph has not already been removed.
// which may happen if more than one field is included in a paragraph.
if (parentParagraph.ParentNode != null)
parentParagraph.Remove();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Open an existing document.
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc");
// Trim trailing and leading whitespaces mail merge values
doc.MailMerge.TrimWhitespaces = false;
// Fill the fields in the document with user data.
doc.MailMerge.Execute(
new string[] { "FullName", "Company", "Address", "Address2", "City" },
new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
dataDir = dataDir + "MailMerge.ExecuteArray_out_.doc";
// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
string fileName = "MailMerge.ExecuteWithRegions.doc";
Document doc = new Document(dataDir + fileName);
int orderId = 10444;
// Perform several mail merge operations populating only part of the document each time.
// Use DataTable as a data source.
DataTable orderTable = GetTestOrder(orderId);
doc.MailMerge.ExecuteWithRegions(orderTable);
// Instead of using DataTable you can create a DataView for custom sort or filter and then mail merge.
DataView orderDetailsView = new DataView(GetTestOrderDetails(orderId));
orderDetailsView.Sort = "ExtendedPrice DESC";
doc.MailMerge.ExecuteWithRegions(orderDetailsView);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static DataTable GetTestOrder(int orderId)
{
DataTable table = ExecuteDataTable(string.Format(
"SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId));
table.TableName = "Orders";
return table;
}
private static DataTable GetTestOrderDetails(int orderId)
{
DataTable table = ExecuteDataTable(string.Format(
"SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId));
table.TableName = "OrderDetails";
return table;
}
/// <summary>
/// Utility function that creates a connection, command,
/// executes the command and return the result in a DataTable.
/// </summary>
private static DataTable ExecuteDataTable(string commandText)
{
// Open the database connection.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
RunExamples.GetDataDir_Database() + "Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
// Create and execute a command.
OleDbCommand cmd = new OleDbCommand(commandText, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
// Close the database.
conn.Close();
return table;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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
private class HandleMergeField : IFieldMergingCallback
{
/// <summary>
/// This handler is called for every mail merge field found in the document,
/// for every record found in the data source.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.Document);
// We decided that we want all boolean values to be output as check box form fields.
if (e.FieldValue is bool)
{
// Move the "cursor" to the current merge field.
mBuilder.MoveToMergeField(e.FieldName);
// It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
string checkBoxName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
// Insert a check box.
mBuilder.InsertCheckBox(checkBoxName, (bool)e.FieldValue, 0);
// Nothing else to do for this field.
return;
}
// We want to insert html during mail merge.
if (e.FieldName == "Body")
{
mBuilder.MoveToMergeField(e.FieldName);
mBuilder.InsertHtml((string)e.FieldValue);
}
// Another example, we want the Subject field to come out as text input form field.
if (e.FieldName == "Subject")
{
mBuilder.MoveToMergeField(e.FieldName);
string textInputName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string)e.FieldValue, 0);
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
private DocumentBuilder mBuilder;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
string fileName = "Template.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Setup mail merge event handler to do the custom work.
doc.MailMerge.FieldMergingCallback = new HandleMergeField();
// Trim trailing and leading whitespaces mail merge values
doc.MailMerge.TrimWhitespaces = false;
// This is the data for mail merge.
String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
"Subject", "Body", "Urgent", "ForReview", "PleaseComment"};
Object[] fieldValues = new Object[] {"Josh", "Jenny", "123456789", "", "Hello",
"<b>HTML Body Test message 1</b>", true, false, true};
// Execute the mail merge.
doc.MailMerge.Execute(fieldNames, fieldValues);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the finished document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
// Do nothing.
}
/// <summary>
/// This is called when mail merge engine encounters Image:XXX merge field in the document.
/// You have a chance to return an Image object, file name or a stream that contains the image.
/// </summary>
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
{
// The field value is a byte array, just cast it and create a stream on it.
MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
// Now the mail merge engine will retrieve the image from the stream.
e.ImageStream = imageStream;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
Document doc = new Document(dataDir + "MailMerge.MergeImage.doc");
// Set up the event handler for image fields.
doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
// Open a database connection.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + RunExamples.GetDataDir_Database()+"Northwind.mdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
// Open the data reader. It needs to be in the normal mode that reads all record at once.
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
IDataReader dataReader = cmd.ExecuteReader();
// Perform mail merge.
doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");
// Close the database.
conn.Close();
dataDir = dataDir + "MailMerge.MergeImage_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
DataSet ds = new DataSet();
ds.ReadXml(dataDir + "Vendors.xml");
// Open a template document.
Document doc = new Document(dataDir + "VendorTemplate.doc");
doc.MailMerge.UseNonMergeFields = true;
// Execute mail merge to fill the template with data from XML using DataSet.
doc.MailMerge.ExecuteWithRegions(ds);
dataDir = dataDir + "MailMergeUsingMustacheSyntax_out_.docx";
// Save the output document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Create the Dataset and read the XML.
DataSet pizzaDs = new DataSet();
// Note: The Datatable.TableNames and the DataSet.Relations are defined implicitly by .NET through ReadXml.
// To see examples of how to set up relations manually check the corresponding documentation of this sample
pizzaDs.ReadXml(dataDir + "CustomerData.xml");
string fileName = "Invoice Template.doc";
// Open the template document.
Document doc = new Document(dataDir + fileName);
// Trim trailing and leading whitespaces mail merge values
doc.MailMerge.TrimWhitespaces = false;
// Execute the nested mail merge with regions
doc.MailMerge.ExecuteWithRegions(pizzaDs);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output to file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public IMailMergeDataSource GetChildDataSource(string tableName)
{
switch (tableName)
{
// Get the child collection to merge it with the region provided with tableName variable.
case "Order":
return new OrderMailMergeDataSource(mCustomers[mRecordIndex].Orders);
default:
return null;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
string fileName = "NestedMailMerge.CustomDataSource.doc";
// Create some data that we will use in the mail merge.
CustomerList customers = new CustomerList();
customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));
// Create some data for nesting in the mail merge.
customers[0].Orders.Add(new Order("Rugby World Cup Cap", 2));
customers[0].Orders.Add(new Order("Rugby World Cup Ball", 1));
customers[1].Orders.Add(new Order("Rugby World Cup Guide", 1));
// Open the template document.
Document doc = new Document(dataDir + fileName);
// To be able to mail merge from your own data source, it must be wrapped
// into an object that implements the IMailMergeDataSource interface.
CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);
// Now you can pass your data source into Aspose.Words.
doc.MailMerge.ExecuteWithRegions(customersDataSource);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Open the database connection.
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataDir + "Customers.mdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
// Get data from a database.
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable data = new DataTable();
da.Fill(data);
// Open the template document.
Document doc = new Document(dataDir + "TestFile.doc");
int counter = 1;
// Loop though all records in the data source.
foreach (DataRow row in data.Rows)
{
// Clone the template instead of loading it from disk (for speed).
Document dstDoc = (Document)doc.Clone(true);
// Execute mail merge.
dstDoc.MailMerge.Execute(row);
// Save the document.
dstDoc.Save(string.Format(dataDir + "TestFile_out_{0}.doc", counter++));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Set the appropriate mail merge clean up options to remove any unused regions from the document.
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions;
//doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields;
//doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveStaticFields;
//doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveEmptyParagraphs;
//doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveUnusedFields;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
string fileName = "TestFile Empty.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// Create a dummy data source containing no data.
DataSet data = new DataSet();
// Set the appropriate mail merge clean up options to remove any unused regions from the document.
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions;
//doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveContainingFields;
//doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveStaticFields;
//doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveEmptyParagraphs;
//doc.MailMerge.CleanupOptions |= MailMergeCleanupOptions.RemoveUnusedFields;
// Execute mail merge which will have no effect as there is no data. However the regions found in the document will be removed
// automatically as they are unused.
doc.MailMerge.ExecuteWithRegions(data);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Open an existing document.
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc");
doc.MailMerge.UseNonMergeFields = true;
// Fill the fields in the document with user data.
doc.MailMerge.Execute(
new string[] { "FullName", "Company", "Address", "Address2", "City" },
new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
dataDir = dataDir + "MailMerge.ExecuteArray_out_.doc";
// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
// Create the Dataset and read the XML.
DataSet customersDs = new DataSet();
customersDs.ReadXml(dataDir + "Customers.xml");
string fileName = "TestFile XML.doc";
// Open a template document.
Document doc = new Document(dataDir + fileName);
// Execute mail merge to fill the template with data from XML using DataTable.
doc.MailMerge.Execute(customersDs.Tables["Customer"]);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithBookmarks();
Document doc = new Document(dataDir + "Bookmarks.doc");
// By index.
Bookmark bookmark1 = doc.Range.Bookmarks[0];
// By name.
Bookmark bookmark2 = doc.Range.Bookmarks["Bookmark2"];
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithBookmarks();
Document doc = new Document(dataDir + "Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];
// Get the name and text of the bookmark.
string name = bookmark.Name;
string text = bookmark.Text;
// Set the name and text of the bookmark.
bookmark.Name = "RenamedBookmark";
bookmark.Text = "This is a new bookmarked text.";
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithBookmarks();
// Create empty document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
// Insert a cell
builder.InsertCell();
// Start bookmark here after calling InsertCell
builder.StartBookmark("MyBookmark");
builder.Write("This is row 1 cell 1");
// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");
builder.EndRow();
// Insert a cell
builder.InsertCell();
builder.Writeln("This is row 2 cell 1");
// Insert a cell
builder.InsertCell();
builder.Writeln("This is row 2 cell 2");
builder.EndRow();
builder.EndTable();
// End of bookmark
builder.EndBookmark("MyBookmark");
dataDir = dataDir + "Bookmark.Table_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithBookmarks();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartBookmark("My Bookmark");
builder.Writeln("Text inside a bookmark.");
builder.StartBookmark("Nested Bookmark");
builder.Writeln("Text inside a NestedBookmark.");
builder.EndBookmark("Nested Bookmark");
builder.Writeln("Text after Nested Bookmark.");
builder.EndBookmark("My Bookmark");
PdfSaveOptions options = new PdfSaveOptions();
options.OutlineOptions.BookmarksOutlineLevels.Add("My Bookmark", 1);
options.OutlineOptions.BookmarksOutlineLevels.Add("Nested Bookmark", 2);
dataDir = dataDir + "Create.Bookmark_out_.pdf";
doc.Save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// 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
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithCharts();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertChart(ChartType.Bar, 432, 252);
Chart chart = shape.Chart;
// Get first series.
ChartSeries series0 = shape.Chart.Series[0];
ChartDataLabelCollection dataLabelCollection = series0.DataLabels;
// Add data label to the first and second point of the first series.
ChartDataLabel chartDataLabel00 = dataLabelCollection.Add(0);
ChartDataLabel chartDataLabel01 = dataLabelCollection.Add(1);
// Set properties.
chartDataLabel00.ShowLegendKey = true;
// By default, when you add data labels to the data points in a pie chart, leader lines are displayed for data labels that are
// positioned far outside the end of data points. Leader lines create a visual connection between a data label and its
// corresponding data point.
chartDataLabel00.ShowLeaderLines = true;
chartDataLabel00.ShowCategoryName = false;
chartDataLabel00.ShowPercentage = false;
chartDataLabel00.ShowSeriesName = true;
chartDataLabel00.ShowValue = true;
chartDataLabel00.Separator = "/";
chartDataLabel01.ShowValue = true;
dataDir = dataDir + @"SimpleBarChart_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithCharts();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
// Get first series.
ChartSeries series0 = shape.Chart.Series[0];
// Get second series.
ChartSeries series1 = shape.Chart.Series[1];
ChartDataPointCollection dataPointCollection = series0.DataPoints;
// Add data point to the first and second point of the first series.
ChartDataPoint dataPoint00 = dataPointCollection.Add(0);
ChartDataPoint dataPoint01 = dataPointCollection.Add(1);
// Set explosion.
dataPoint00.Explosion = 50;
// Set marker symbol and size.
dataPoint00.Marker.Symbol = MarkerSymbol.Circle;
dataPoint00.Marker.Size = 15;
dataPoint01.Marker.Symbol = MarkerSymbol.Diamond;
dataPoint01.Marker.Size = 20;
// Add data point to the third point of the second series.
ChartDataPoint dataPoint12 = series1.DataPoints.Add(2);
dataPoint12.InvertIfNegative = true;
dataPoint12.Marker.Symbol = MarkerSymbol.Star;
dataPoint12.Marker.Size = 20;
dataDir = dataDir + @"SingleChartDataPoint_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Specifies whether by default the parent element shall inverts its colors if the value is negative.
series0.InvertIfNegative = true;
// Set default marker symbol and size.
series0.Marker.Symbol = MarkerSymbol.Circle;
series0.Marker.Size = 15;
series1.Marker.Symbol = MarkerSymbol.Star;
series1.Marker.Size = 10;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Get first series.
ChartSeries series0 = shape.Chart.Series[0];
// Get second series.
ChartSeries series1 = shape.Chart.Series[1];
// Change first series name.
series0.Name = "My Name1";
// Change second series name.
series1.Name = "My Name2";
// You can also specify whether the line connecting the points on the chart shall be smoothed using Catmull-Rom splines.
series0.Smooth = true;
series1.Smooth = true;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithComments();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");
Comment comment = new Comment(doc, "Awais Hafeez", "AH", DateTime.Today);
builder.CurrentParagraph.AppendChild(comment);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
dataDir = dataDir + "Comments_out_.doc";
// Save the document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Some text is added.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithComments();
Document doc = new Document();
Paragraph para1 = new Paragraph(doc);
Run run1 = new Run(doc, "Some ");
Run run2 = new Run(doc, "text ");
para1.AppendChild(run1);
para1.AppendChild(run2);
doc.FirstSection.Body.AppendChild(para1);
Paragraph para2 = new Paragraph(doc);
Run run3 = new Run(doc, "is ");
Run run4 = new Run(doc, "added ");
para2.AppendChild(run3);
para2.AppendChild(run4);
doc.FirstSection.Body.AppendChild(para2);
Comment comment = new Comment(doc, "Awais Hafeez", "AH", DateTime.Today);
comment.Paragraphs.Add(new Paragraph(doc));
comment.FirstParagraph.Runs.Add(new Run(doc, "Comment text."));
CommentRangeStart commentRangeStart = new CommentRangeStart(doc, comment.Id);
CommentRangeEnd commentRangeEnd = new CommentRangeEnd(doc, comment.Id);
run1.ParentNode.InsertAfter(commentRangeStart, run1);
run3.ParentNode.InsertAfter(commentRangeEnd, run3);
commentRangeEnd.ParentNode.InsertAfter(comment, commentRangeEnd);
dataDir = dataDir + "Anchor.Comment_out_.doc";
// Save the document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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);
// 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
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();
// Load the document from disk.
Document doc = new Document(dataDir + "TestFile.doc");
Document clone = doc.Clone();
dataDir = dataDir + "TestFile_clone_out_.doc";
// Save the document to disk.
clone.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
Document doc = new Document();
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.ComboBox, MarkupLevel.Block);
sdt.ListItems.Add(new SdtListItem("Choose an item", "-1"));
sdt.ListItems.Add(new SdtListItem("Item 1", "1"));
sdt.ListItems.Add(new SdtListItem("Item 2", "2"));
doc.FirstSection.Body.AppendChild(sdt);
dataDir = dataDir + "ComboBoxContentControl_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static ArrayList ExtractContent(Node startNode, Node endNode, bool isInclusive)
{
// First check that the nodes passed to this method are valid for use.
VerifyParameterNodes(startNode, endNode);
// Create a list to store the extracted nodes.
ArrayList nodes = new ArrayList();
// Keep a record of the original nodes passed to this method so we can split marker nodes if needed.
Node originalStartNode = startNode;
Node originalEndNode = endNode;
// Extract content based on block level nodes (paragraphs and tables). Traverse through parent nodes to find them.
// We will split the content of first and last nodes depending if the marker nodes are inline
while (startNode.ParentNode.NodeType != NodeType.Body)
startNode = startNode.ParentNode;
while (endNode.ParentNode.NodeType != NodeType.Body)
endNode = endNode.ParentNode;
bool isExtracting = true;
bool isStartingNode = true;
bool isEndingNode = false;
// The current node we are extracting from the document.
Node currNode = startNode;
// Begin extracting content. Process all block level nodes and specifically split the first and last nodes when needed so paragraph formatting is retained.
// Method is little more complex than a regular extractor as we need to factor in extracting using inline nodes, fields, bookmarks etc as to make it really useful.
while (isExtracting)
{
// Clone the current node and its children to obtain a copy.
CompositeNode cloneNode = (CompositeNode)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.
if (isStartingNode)
{
ProcessMarker(cloneNode, nodes, originalStartNode, isInclusive, isStartingNode, isEndingNode);
isStartingNode = false;
}
// Conditional needs to be separate as the block level start and end markers maybe the same node.
if (isEndingNode)
{
ProcessMarker(cloneNode, nodes, originalEndNode, isInclusive, isStartingNode, isEndingNode);
isExtracting = false;
}
}
else
// Node is not a start or end marker, simply add the copy to the list.
nodes.Add(cloneNode);
// Move to the next node and extract it. If next node is null that means the rest of the content is found in a different section.
if (currNode.NextSibling == null && isExtracting)
{
// Move to the next section.
Section nextSection = (Section)currNode.GetAncestor(NodeType.Section).NextSibling;
currNode = nextSection.Body.FirstChild;
}
else
{
// Move to the next node in the body.
currNode = currNode.NextSibling;
}
}
// Return the nodes between the node markers.
return nodes;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void VerifyParameterNodes(Node startNode, Node endNode)
{
// The order in which these checks are done is important.
if (startNode == null)
throw new ArgumentException("Start node cannot be null");
if (endNode == null)
throw new ArgumentException("End node cannot be null");
if (!startNode.Document.Equals(endNode.Document))
throw new ArgumentException("Start node and end node must belong to the same document");
if (startNode.GetAncestor(NodeType.Body) == null || endNode.GetAncestor(NodeType.Body) == null)
throw new ArgumentException("Start node and end node must be a child or descendant of a body");
// Check the end node is after the start node in the DOM tree
// First check if they are in different sections, then if they're not check their position in the body of the same section they are in.
Section startSection = (Section)startNode.GetAncestor(NodeType.Section);
Section endSection = (Section)endNode.GetAncestor(NodeType.Section);
int startIndex = startSection.ParentNode.IndexOf(startSection);
int endIndex = endSection.ParentNode.IndexOf(endSection);
if (startIndex == endIndex)
{
if (startSection.Body.IndexOf(startNode) > endSection.Body.IndexOf(endNode))
throw new ArgumentException("The end node must be after the start node in the body");
}
else if (startIndex > endIndex)
throw new ArgumentException("The section of end node must be after the section start node");
}
private static bool IsInline(Node node)
{
// Test if the node is desendant of a Paragraph or Table node and also is not a paragraph or a table a paragraph inside a comment class which is decesant of a pararaph is possible.
return ((node.GetAncestor(NodeType.Paragraph) != null || node.GetAncestor(NodeType.Table) != null) && !(node.NodeType == NodeType.Paragraph || node.NodeType == NodeType.Table));
}
private static void ProcessMarker(CompositeNode cloneNode, ArrayList nodes, Node node, bool isInclusive, bool isStartMarker, bool isEndMarker)
{
// If we are dealing with a block level node just see if it should be included and add it to the list.
if (!IsInline(node))
{
// Don't add the node twice if the markers are the same node
if (!(isStartMarker && isEndMarker))
{
if (isInclusive)
nodes.Add(cloneNode);
}
return;
}
// If a marker is a FieldStart node check if it's to be included or not.
// We assume for simplicity that the FieldStart and FieldEnd appear in the same paragraph.
if (node.NodeType == NodeType.FieldStart)
{
// If the marker is a start node and is not be included then skip to the end of the field.
// If the marker is an end node and it is to be included then move to the end field so the field will not be removed.
if ((isStartMarker && !isInclusive) || (!isStartMarker && isInclusive))
{
while (node.NextSibling != null && node.NodeType != NodeType.FieldEnd)
node = node.NextSibling;
}
}
// If either marker is part of a comment then to include the comment itself we need to move the pointer forward to the Comment
// node found after the CommentRangeEnd node.
if (node.NodeType == NodeType.CommentRangeEnd)
{
while (node.NextSibling != null && node.NodeType != NodeType.Comment)
node = node.NextSibling;
}
// Find the corresponding node in our cloned node by index and return it.
// If the start and end node are the same some child nodes might already have been removed. Subtract the
// difference to get the right index.
int indexDiff = node.ParentNode.ChildNodes.Count - cloneNode.ChildNodes.Count;
// Child node count identical.
if (indexDiff == 0)
node = cloneNode.ChildNodes[node.ParentNode.IndexOf(node)];
else
node = cloneNode.ChildNodes[node.ParentNode.IndexOf(node) - indexDiff];
// Remove the nodes up to/from the marker.
bool isSkip = false;
bool isProcessing = true;
bool isRemoving = isStartMarker;
Node nextNode = cloneNode.FirstChild;
while (isProcessing && nextNode != null)
{
Node currentNode = nextNode;
isSkip = false;
if (currentNode.Equals(node))
{
if (isStartMarker)
{
isProcessing = false;
if (isInclusive)
isRemoving = false;
}
else
{
isRemoving = true;
if (isInclusive)
isSkip = true;
}
}
nextNode = nextNode.NextSibling;
if (isRemoving && !isSkip)
currentNode.Remove();
}
// After processing the composite node may become empty. If it has don't include it.
if (!(isStartMarker && isEndMarker))
{
if (cloneNode.HasChildNodes)
nodes.Add(cloneNode);
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static Document GenerateDocument(Document srcDoc, ArrayList nodes)
{
// Create a blank document.
Document dstDoc = new Document();
// Remove the first paragraph from the empty document.
dstDoc.FirstSection.Body.RemoveAllChildren();
// Import each node from the list into the new document. Keep the original formatting of the node.
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting);
foreach (Node node in nodes)
{
Node importNode = importer.ImportNode(node, true);
dstDoc.FirstSection.Body.AppendChild(importNode);
}
// Return the generated document.
return dstDoc;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
// docA now contains changes as revisions.
docA.Compare(docB, "user", DateTime.Now);
if (docA.Revisions.Count == 0)
Console.WriteLine("Documents are equal");
else
Console.WriteLine("Documents are not equal");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
// docA now contains changes as revisions.
docA.Compare(docB, "user", DateTime.Now);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Clones and copies headers/footers form the previous section to the specified section.
/// </summary>
private static void CopyHeadersFootersFromPreviousSection(Section section)
{
Section previousSection = (Section)section.PreviousSibling;
if (previousSection == null)
return;
section.HeadersFooters.Clear();
foreach (HeaderFooter headerFooter in previousSection.HeadersFooters)
section.HeadersFooters.Add(headerFooter.Clone(true));
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Section currentSection = builder.CurrentSection;
PageSetup pageSetup = currentSection.PageSetup;
// Specify if we want headers/footers of the first page to be different from other pages.
// You can also use PageSetup.OddAndEvenPagesHeaderFooter property to specify
// different headers/footers for odd and even pages.
pageSetup.DifferentFirstPageHeaderFooter = true;
// --- Create header for the first page. ---
pageSetup.HeaderDistance = 20;
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
// Set font properties for header text.
builder.Font.Name = "Arial";
builder.Font.Bold = true;
builder.Font.Size = 14;
// Specify header title for the first page.
builder.Write("Aspose.Words Header/Footer Creation Primer - Title Page.");
// --- Create header for pages other than first. ---
pageSetup.HeaderDistance = 20;
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
// Insert absolutely positioned image into the top/left corner of the header.
// Distance from the top/left edges of the page is set to 10 points.
string imageFileName = dataDir + "Aspose.Words.gif";
builder.InsertImage(imageFileName, RelativeHorizontalPosition.Page, 10, RelativeVerticalPosition.Page, 10, 50, 50, WrapType.Through);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
// Specify another header title for other pages.
builder.Write("Aspose.Words Header/Footer Creation Primer.");
// --- Create footer for pages other than first. ---
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
// We use table with two cells to make one part of the text on the line (with page numbering)
// to be aligned left, and the other part of the text (with copyright) to be aligned right.
builder.StartTable();
// Clear table borders.
builder.CellFormat.ClearFormatting();
builder.InsertCell();
// Set first cell to 1/3 of the page width.
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100 / 3);
// Insert page numbering text here.
// It uses PAGE and NUMPAGES fields to auto calculate current page number and total number of pages.
builder.Write("Page ");
builder.InsertField("PAGE", "");
builder.Write(" of ");
builder.InsertField("NUMPAGES", "");
// Align this text to the left.
builder.CurrentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.InsertCell();
// Set the second cell to 2/3 of the page width.
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100 * 2 / 3);
builder.Write("(C) 2001 Aspose Pty Ltd. All rights reserved.");
// Align this text to the right.
builder.CurrentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.EndRow();
builder.EndTable();
builder.MoveToDocumentEnd();
// Make page break to create a second page on which the primary headers/footers will be seen.
builder.InsertBreak(BreakType.PageBreak);
// Make section break to create a third page with different page orientation.
builder.InsertBreak(BreakType.SectionBreakNewPage);
// Get the new section and its page setup.
currentSection = builder.CurrentSection;
pageSetup = currentSection.PageSetup;
// Set page orientation of the new section to landscape.
pageSetup.Orientation = Orientation.Landscape;
// This section does not need different first page header/footer.
// We need only one title page in the document and the header/footer for this page
// has already been defined in the previous section
pageSetup.DifferentFirstPageHeaderFooter = false;
// This section displays headers/footers from the previous section by default.
// Call currentSection.HeadersFooters.LinkToPrevious(false) to cancel this.
// Page width is different for the new section and therefore we need to set
// a different cell widths for a footer table.
currentSection.HeadersFooters.LinkToPrevious(false);
// If we want to use the already existing header/footer set for this section
// but with some minor modifications then it may be expedient to copy headers/footers
// from the previous section and apply the necessary modifications where we want them.
CopyHeadersFootersFromPreviousSection(currentSection);
// Find the footer that we want to change.
HeaderFooter primaryFooter = currentSection.HeadersFooters[HeaderFooterType.FooterPrimary];
Row row = primaryFooter.Tables[0].FirstRow;
row.FirstCell.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100 / 3);
row.LastCell.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100 * 2 / 3);
dataDir = dataDir + "HeaderFooter.Primer_out_.doc";
// Save the resulting document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Properties.doc");
CustomDocumentProperties props = doc.CustomDocumentProperties;
if (props["Authorized"] == null)
{
props.Add("Authorized", true);
props.Add("Authorized By", "John Smith");
props.Add("Authorized Date", DateTime.Today);
props.Add("Authorized Revision", doc.BuiltInDocumentProperties.RevisionNumber);
props.Add("Authorized Amount", 123.45);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Properties.doc");
doc.CustomDocumentProperties.Remove("Authorized Date");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string fileName = dataDir + "Properties.doc";
Document doc = new Document(fileName);
Console.WriteLine("1. Document name: {0}", fileName);
Console.WriteLine("2. Built-in Properties");
foreach (DocumentProperty prop in doc.BuiltInDocumentProperties)
Console.WriteLine("{0} : {1}", prop.Name, prop.Value);
Console.WriteLine("3. Custom Properties");
foreach (DocumentProperty prop in doc.CustomDocumentProperties)
Console.WriteLine("{0} : {1}", prop.Name, prop.Value);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");
// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");
builder.EndRow();
// Insert a cell
builder.InsertCell();
// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;
builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");
// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");
builder.EndRow();
builder.EndTable();
dataDir = dataDir + "DocumentBuilderBuildTable_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartBookmark("FineBookmark");
builder.Writeln("This is just a fine bookmark.");
builder.EndBookmark("FineBookmark");
dataDir = dataDir + "DocumentBuilderInsertBookmark_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("This is page 1.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("This is page 2.");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("This is page 3.");
dataDir = dataDir + "DocumentBuilderInsertBreak_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertCheckBox("CheckBox", true, true, 0);
dataDir = dataDir + "DocumentBuilderInsertCheckBoxFormField_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
string[] items = { "One", "Two", "Three" };
builder.InsertComboBox("DropDown", items, 0);
dataDir = dataDir + "DocumentBuilderInsertComboBoxFormField_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertHtml(
"<P align='right'>Paragraph right</P>" +
"<b>Implicit paragraph left</b>" +
"<div align='center'>Div center</div>" +
"<h1 align='left'>Heading 1 left.</h1>");
dataDir = dataDir + "DocumentBuilderInsertHtml_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertOleObject("http://www.aspose.com", "htmlfile", true, true, null);
dataDir = dataDir + "DocumentBuilderInsertOleObject_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("Heading 1");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("Heading 2");
builder.Writeln("Heading 3");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 3.1");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;
builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");
doc.UpdateFields();
dataDir = dataDir + "DocumentBuilderInsertTableOfContents_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertTextInput("TextInput", TextFormFieldType.Regular, "", "Hello", 0);
dataDir = dataDir + "DocumentBuilderInsertTextInputFormField_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
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 class InsertTCFieldHandler : IReplacingCallback
{
// Store the text and switches to be used for the TC fields.
private string mFieldText;
private string mFieldSwitches;
/// <summary>
/// The switches to use for each TC field. Can be an empty string or null.
/// </summary>
public InsertTCFieldHandler(string switches)
: this(string.Empty, switches)
{
mFieldSwitches = switches;
}
/// <summary>
/// The display text and switches to use for each TC field. Display name can be an empty string or null.
/// </summary>
public InsertTCFieldHandler(string text, string switches)
{
mFieldText = text;
mFieldSwitches = switches;
}
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
{
// Create a builder to insert the field.
DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
// Move to the first node of the match.
builder.MoveTo(args.MatchNode);
// If the user specified text to be used in the field as display text then use that, otherwise use the
// match string as the display text.
string insertText;
if (!string.IsNullOrEmpty(mFieldText))
insertText = mFieldText;
else
insertText = args.Match.Value;
// Insert the TC field before this node using the specified string as the display text and user defined switches.
builder.InsertField(string.Format("TC \"{0}\" {1}", insertText, mFieldSwitches));
// We have done what we want so skip replacement.
return ReplaceAction.Skip;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// The newly inserted table of contents will be initially empty.
// It needs to be populated by updating the fields in the document.
doc.UpdateFields();
dataDir = dataDir + "DocumentBuilderInsertTOC_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
doc.UpdateFields();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Shows how to access the current node in a document builder.
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
Node curNode = builder.CurrentNode;
Paragraph curParagraph = builder.CurrentParagraph;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Create a blank document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;
// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header First");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header Even");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header Odd");
// Create three pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page3");
dataDir = dataDir + "DocumentBuilder.HeadersAndFooters_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToBookmark("CoolBookmark");
builder.Writeln("This is a very cool bookmark.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToBookmark("CoolBookmark", false, true);
builder.Writeln("This is a very cool bookmark.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();
Console.WriteLine("\nThis is the end of the document.");
builder.MoveToDocumentStart();
Console.WriteLine("\nThis is the beginning of the document.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField("NiceMergeField");
builder.Writeln("This is a very nice merge field.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveTo(doc.FirstSection.Body.LastParagraph);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Parameters are 0-index. Moves to third paragraph.
builder.MoveToParagraph(2, 0);
builder.Writeln("This is the 3rd paragraph.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Parameters are 0-index. Moves to third section.
builder.MoveToSection(2);
builder.Writeln("This is the 3rd section.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// All parameters are 0-index. Moves to the 2nd table, 3rd row, 5th cell.
builder.MoveToCell(1, 2, 4, 0);
builder.Writeln("Hello World!");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;
// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;
builder.Write("I'm a formatted paragraph with double border and nice shading.");
dataDir = dataDir + "DocumentBuilderApplyBordersAndShadingToParagraph_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set paragraph style
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Title;
builder.Write("Hello");
dataDir = dataDir + "DocumentBuilderApplyParagraphStyle_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set font formatting properties
Font font = builder.Font;
font.Bold = true;
font.Color = System.Drawing.Color.DarkBlue;
font.Italic = true;
font.Name = "Arial";
font.Size = 24;
font.Spacing = 5;
font.Underline = Underline.Double;
// Output formatted text
builder.Writeln("I'm a very nice formatted string.");
dataDir = dataDir + "DocumentBuilderSetFontFormatting_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.ListFormat.ApplyNumberDefault();
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.ListIndent();
builder.Writeln("Item 2.1");
builder.Writeln("Item 2.2");
builder.ListFormat.ListIndent();
builder.Writeln("Item 2.2.1");
builder.Writeln("Item 2.2.2");
builder.ListFormat.ListOutdent();
builder.Writeln("Item 2.3");
builder.ListFormat.ListOutdent();
builder.Writeln("Item 3");
builder.ListFormat.RemoveNumbers();
dataDir = dataDir + "DocumentBuilderSetMultilevelListFormatting_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set page properties
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.LeftMargin = 50;
builder.PageSetup.PaperSize = PaperSize.Paper10x14;
dataDir = dataDir + "DocumentBuilderSetPageSetupAndSectionFormatting_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set paragraph formatting properties
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphFormat.LeftIndent = 50;
paragraphFormat.RightIndent = 50;
paragraphFormat.SpaceAfter = 25;
// Output text
builder.Writeln("I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
builder.Writeln("I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");
dataDir = dataDir + "DocumentBuilderSetParagraphFormatting_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
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
// 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.GetChild(NodeType.Paragraph, 6, true);
Paragraph endPara = (Paragraph)doc.FirstSection.GetChild(NodeType.Paragraph, 10, true);
// Extract the content between these nodes in the document. Include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startPara, endPara, true);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Gather a list of the paragraphs using the respective heading styles.
ArrayList parasStyleHeading1 = Common.ParagraphsByStyleName(doc, "Heading 1");
ArrayList parasStyleHeading3 = Common.ParagraphsByStyleName(doc, "Heading 3");
// Use the first instance of the paragraphs with those styles.
Node startPara1 = (Node)parasStyleHeading1[0];
Node endPara1 = (Node)parasStyleHeading3[0];
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startPara1, endPara1, false);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Retrieve a paragraph from the first section.
Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 7, true);
// Use some runs for extraction.
Run startRun = para.Runs[1];
Run endRun = para.Runs[4];
// Extract the content between these nodes in the document. Include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startRun, endRun, true);
// Get the node from the list. There should only be one paragraph returned in the list.
Node node = (Node)extractedNodes[0];
// Print the text of this node to the console.
Console.WriteLine(node.ToString(SaveFormat.Text));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Open the document we want to convert.
Document doc = new Document(dataDir + "Visitor.ToText.doc");
// Create an object that inherits from the DocumentVisitor class.
MyDocToTxtWriter myConverter = new MyDocToTxtWriter();
// This is the well known Visitor pattern. Get the model to accept a visitor.
// The model will iterate through itself by calling the corresponding methods
// on the visitor object (this is called visiting).
//
// Note that every node in the object model has the Accept method so the visiting
// can be executed not only for the whole document, but for any node in the document.
doc.Accept(myConverter);
// Once the visiting is complete, we can retrieve the result of the operation,
// that in this example, has accumulated in the visitor.
Console.WriteLine(myConverter.GetText());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
internal class MyDocToTxtWriter : DocumentVisitor
{
public MyDocToTxtWriter()
{
mIsSkipText = false;
mBuilder = new StringBuilder();
}
/// <summary>
/// Gets the plain text of the document that was accumulated by the visitor.
/// </summary>
public string GetText()
{
return mBuilder.ToString();
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// </summary>
public override VisitorAction VisitRun(Run run)
{
AppendText(run.Text);
// Let the visitor continue visiting other nodes.
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldStart node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldStart(FieldStart fieldStart)
{
// In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
// after a field start character. We want to skip field codes and output field
// result only, therefore we use a flag to suspend the output while inside a field code.
//
// Note this is a very simplistic implementation and will not work very well
// if you have nested fields in a document.
mIsSkipText = true;
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldSeparator node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
{
// Once reached a field separator node, we enable the output because we are
// now entering the field result nodes.
mIsSkipText = false;
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldEnd node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
{
// Make sure we enable the output when reached a field end because some fields
// do not have field separator and do not have field result.
mIsSkipText = false;
return VisitorAction.Continue;
}
/// <summary>
/// Called when visiting of a Paragraph node is ended in the document.
/// </summary>
public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
{
// When outputting to plain text we output Cr+Lf characters.
AppendText(ControlChar.CrLf);
return VisitorAction.Continue;
}
public override VisitorAction VisitBodyStart(Body body)
{
// We can detect beginning and end of all composite nodes such as Section, Body,
// Table, Paragraph etc and provide custom handling for them.
mBuilder.Append("*** Body Started ***\r\n");
return VisitorAction.Continue;
}
public override VisitorAction VisitBodyEnd(Body body)
{
mBuilder.Append("*** Body Ended ***\r\n");
return VisitorAction.Continue;
}
/// <summary>
/// Called when a HeaderFooter node is encountered in the document.
/// </summary>
public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
{
// Returning this value from a visitor method causes visiting of this
// node to stop and move on to visiting the next sibling node.
// The net effect in this example is that the text of headers and footers
// is not included in the resulting output.
return VisitorAction.SkipThisNode;
}
/// <summary>
/// Adds text to the current output. Honours the enabled/disabled output flag.
/// </summary>
private void AppendText(string text)
{
if (!mIsSkipText)
mBuilder.Append(text);
}
private readonly StringBuilder mBuilder;
private bool mIsSkipText;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Use a document builder to retrieve the field start of a merge field.
DocumentBuilder builder = new DocumentBuilder(doc);
// Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field.
// We could also get FieldStarts of a field using GetChildNode method as in the other examples.
builder.MoveToMergeField("Fullname", false, false);
// The builder cursor should be positioned at the start of the field.
FieldStart startField = (FieldStart)builder.CurrentNode;
Paragraph endPara = (Paragraph)doc.FirstSection.GetChild(NodeType.Paragraph, 5, true);
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startField, endPara, false);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Enter a dummy field into the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField("MERGEFIELD Field");
// GetText will retrieve all field codes and special characters
Console.WriteLine("GetText() Result: " + doc.GetText());
// ToString will export the node to the specified format. When converted to text it will not retrieve fields code
// or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
// This is the same as "viewing" the document as if it was opened in a text editor.
Console.WriteLine("ToString() Result: " + doc.ToString(SaveFormat.Text));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Load the template document.
Document doc = new Document(dataDir + "TestFile.doc");
string variables = "";
foreach (DictionaryEntry entry in doc.Variables)
{
string name = entry.Key.ToString();
string value = entry.Value.ToString();
if (variables == "")
{
// Do something useful.
variables = "Name: " + name + "," + "Value: {1}" + value;
}
else
{
variables = variables + "Name: " + name + "," + "Value: {1}" + value;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
static void InsertDocument(Node insertAfterNode, Document srcDoc)
{
// Make sure that the node is either a paragraph or table.
if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
(!insertAfterNode.NodeType.Equals(NodeType.Table)))
throw new ArgumentException("The destination node should be either a paragraph or table.");
// We will be inserting into the parent of the destination paragraph.
CompositeNode dstStory = insertAfterNode.ParentNode;
// This object will be translating styles and lists during the import.
NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);
// Loop through all sections in the source document.
foreach (Section srcSection in srcDoc.Sections)
{
// Loop through all block level nodes (paragraphs and tables) in the body of the section.
foreach (Node srcNode in srcSection.Body)
{
// Let's skip the node if it is a last empty paragraph in a section.
if (srcNode.NodeType.Equals(NodeType.Paragraph))
{
Paragraph para = (Paragraph)srcNode;
if (para.IsEndOfSection && !para.HasChildNodes)
continue;
}
// This creates a clone of the node, suitable for insertion into the destination document.
Node newNode = importer.ImportNode(srcNode, true);
// Insert new node after the reference node.
dstStory.InsertAfter(newNode, insertAfterNode);
insertAfterNode = newNode;
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document mainDoc = new Document(dataDir + "InsertDocument1.doc");
Document subDoc = new Document(dataDir + "InsertDocument2.doc");
Bookmark bookmark = mainDoc.Range.Bookmarks["insertionPlace"];
InsertDocument(bookmark.BookmarkStart.ParentNode, subDoc);
dataDir = dataDir + "InsertDocumentAtBookmark_out_.doc";
mainDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open the main document.
Document mainDoc = new Document(dataDir + "InsertDocument1.doc");
// Add a handler to MergeField event
mainDoc.MailMerge.FieldMergingCallback = new InsertDocumentAtMailMergeHandler();
// The main document has a merge field in it called "Document_1".
// The corresponding data for this field contains fully qualified path to the document
// that should be inserted to this field.
mainDoc.MailMerge.Execute(
new string[] { "Document_1" },
new string[] { dataDir + "InsertDocument2.doc" });
dataDir = dataDir + "InsertDocumentAtMailMerge_out_.doc";
mainDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class InsertDocumentAtMailMergeBlobHandler : IFieldMergingCallback
{
/// <summary>
/// This handler makes special processing for the "Document_1" field.
/// The field value contains the path to load the document.
/// We load the document and insert it into the current merge field.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (e.DocumentFieldName == "Document_1")
{
// Use document builder to navigate to the merge field with the specified name.
DocumentBuilder builder = new DocumentBuilder(e.Document);
builder.MoveToMergeField(e.DocumentFieldName);
// Load the document from the blob field.
MemoryStream stream = new MemoryStream((byte[])e.FieldValue);
Document subDoc = new Document(stream);
// Insert the document.
InsertDocument(builder.CurrentParagraph, subDoc);
// The paragraph that contained the merge field might be empty now and you probably want to delete it.
if (!builder.CurrentParagraph.HasChildNodes)
builder.CurrentParagraph.Remove();
// Indicate to the mail merge engine that we have inserted what we wanted.
e.Text = null;
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class InsertDocumentAtMailMergeHandler : IFieldMergingCallback
{
/// <summary>
/// This handler makes special processing for the "Document_1" field.
/// The field value contains the path to load the document.
/// We load the document and insert it into the current merge field.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (e.DocumentFieldName == "Document_1")
{
// Use document builder to navigate to the merge field with the specified name.
DocumentBuilder builder = new DocumentBuilder(e.Document);
builder.MoveToMergeField(e.DocumentFieldName);
// The name of the document to load and insert is stored in the field value.
Document subDoc = new Document((string)e.FieldValue);
// Insert the document.
InsertDocument(builder.CurrentParagraph, subDoc);
// The paragraph that contained the merge field might be empty now and you probably want to delete it.
if (!builder.CurrentParagraph.HasChildNodes)
builder.CurrentParagraph.Remove();
// Indicate to the mail merge engine that we have inserted what we wanted.
e.Text = null;
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document mainDoc = new Document(dataDir + "InsertDocument1.doc");
FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new InsertDocumentAtReplaceHandler();
mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"),"" , options);
dataDir = dataDir + "InsertDocumentAtReplace_out_.doc";
mainDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
Document subDoc = new Document(RunExamples.GetDataDir_WorkingWithDocument() + "InsertDocument2.doc");
// Insert a document after the paragraph, containing the match text.
Paragraph para = (Paragraph)e.MatchNode.ParentNode;
InsertDocument(para, subDoc);
// Remove the paragraph with the match text.
para.Remove();
return ReplaceAction.Skip;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Inserts content of the external document after the specified node.
/// </summary>
/// <param name="insertAfterNode">Node in the destination document after which the content
/// should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="srcDoc">The document to insert.</param>
static void InsertDocumentWithSectionFormatting(Node insertAfterNode, Document srcDoc)
{
// Make sure that the node is either a pargraph or table.
if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
(!insertAfterNode.NodeType.Equals(NodeType.Table)))
throw new ArgumentException("The destination node should be either a paragraph or table.");
// Document to insert srcDoc into.
Document dstDoc = (Document)insertAfterNode.Document;
// To retain section formatting, split the current section into two at the marker node and then import the content from srcDoc as whole sections.
// The section of the node which the insert marker node belongs to
Section currentSection = (Section)insertAfterNode.GetAncestor(NodeType.Section);
// Don't clone the content inside the section, we just want the properties of the section retained.
Section cloneSection = (Section)currentSection.Clone(false);
// However make sure the clone section has a body, but no empty first paragraph.
cloneSection.EnsureMinimum();
cloneSection.Body.FirstParagraph.Remove();
// Insert the cloned section into the document after the original section.
insertAfterNode.Document.InsertAfter(cloneSection, currentSection);
// Append all nodes after the marker node to the new section. This will split the content at the section level at
// the marker so the sections from the other document can be inserted directly.
Node currentNode = insertAfterNode.NextSibling;
while (currentNode != null)
{
Node nextNode = currentNode.NextSibling;
cloneSection.Body.AppendChild(currentNode);
currentNode = nextNode;
}
// This object will be translating styles and lists during the import.
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.UseDestinationStyles);
// Loop through all sections in the source document.
foreach (Section srcSection in srcDoc.Sections)
{
Node newNode = importer.ImportNode(srcSection, true);
// Append each section to the destination document. Start by inserting it after the split section.
dstDoc.InsertAfter(newNode, currentSection);
currentSection = (Section)newNode;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(inputFileName);
ProtectionType protectionType = doc.ProtectionType;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(inputFileName);
doc.Protect(ProtectionType.AllowOnlyFormFields, "password");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(inputFileName);
doc.Unprotect();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
string fileName = "TestFile.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void RemovePageBreaks(Document doc)
{
// Retrieve all paragraphs in the document.
NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);
// Iterate through all paragraphs
foreach (Paragraph para in paragraphs)
{
// If the paragraph has a page break before set then clear it.
if (para.ParagraphFormat.PageBreakBefore)
para.ParagraphFormat.PageBreakBefore = false;
// Check all runs in the paragraph for page breaks and remove them.
foreach (Run run in para.Runs)
{
if (run.Text.Contains(ControlChar.PageBreak))
run.Text = run.Text.Replace(ControlChar.PageBreak, string.Empty);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void RemoveSectionBreaks(Document doc)
{
// Loop through all sections starting from the section that precedes the last one
// and moving to the first section.
for (int i = doc.Sections.Count - 2; i >= 0; i--)
{
// Copy the content of the current section to the beginning of the last section.
doc.LastSection.PrependContent(doc.Sections[i]);
// Remove the copied section.
doc.Sections[i].Remove();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
Document doc = new Document(dataDir + "HeaderFooter.RemoveFooters.doc");
foreach (Section section in doc)
{
// Up to three different footers are possible in a section (for first, even and odd pages).
// We check and delete all of them.
HeaderFooter footer;
footer = section.HeadersFooters[HeaderFooterType.FooterFirst];
if (footer != null)
footer.Remove();
// Primary footer is the footer used for odd pages.
footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
if (footer != null)
footer.Remove();
footer = section.HeadersFooters[HeaderFooterType.FooterEven];
if (footer != null)
footer.Remove();
}
dataDir = dataDir + "HeaderFooter.RemoveFooters_out_.doc";
// Save the document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithStyles();
// Open a document which contains a TOC.
Document doc = new Document(dataDir + "Document.TableOfContents.doc");
// Remove the first table of contents from the document.
RemoveTableOfContents(doc, 0);
dataDir = dataDir + "Document.TableOfContentsRemoveToc_out_.doc";
// Save the output.
doc.Save(dataDir);
Console.WriteLine("\nSpecified TOC from a document removed successfully.\nFile saved at " + dataDir);
}
/// <summary>
/// Removes the specified table of contents field from the document.
/// </summary>
/// <param name="doc">The document to remove the field from.</param>
/// <param name="index">The zero-based index of the TOC to remove.</param>
public static void RemoveTableOfContents(Document doc, int index)
{
// Store the FieldStart nodes of TOC fields in the document for quick access.
ArrayList fieldStarts = new ArrayList();
// This is a list to store the nodes found inside the specified TOC. They will be removed
// at the end of this method.
ArrayList nodeList = new ArrayList();
foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true))
{
if (start.FieldType == FieldType.FieldTOC)
{
// Add all FieldStarts which are of type FieldTOC.
fieldStarts.Add(start);
}
}
// Ensure the TOC specified by the passed index exists.
if (index > fieldStarts.Count - 1)
throw new ArgumentOutOfRangeException("TOC index is out of range");
bool isRemoving = true;
// Get the FieldStart of the specified TOC.
Node currentNode = (Node)fieldStarts[index];
while (isRemoving)
{
// It is safer to store these nodes and delete them all at once later.
nodeList.Add(currentNode);
currentNode = currentNode.NextPreOrder(doc);
// Once we encounter a FieldEnd node of type FieldTOC then we know we are at the end
// of the current TOC and we can stop here.
if (currentNode.NodeType == NodeType.FieldEnd)
{
FieldEnd fieldEnd = (FieldEnd)currentNode;
if (fieldEnd.FieldType == FieldType.FieldTOC)
isRemoving = false;
}
}
// Remove all nodes found in the specified TOC.
foreach (Node node in nodeList)
{
node.Remove();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
Document doc = new Document();
StructuredDocumentTag sdtRichText = new StructuredDocumentTag(doc, SdtType.RichText, MarkupLevel.Block);
Paragraph para = new Paragraph(doc);
Run run = new Run(doc);
run.Text = "Hello World";
run.Font.Color = Color.Green;
para.Runs.Add(run);
sdtRichText.ChildNodes.Add(para);
doc.FirstSection.Body.AppendChild(sdtRichText);
dataDir = dataDir + "RichTextBoxContentControl_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Load the template document.
Document doc = new Document(dataDir + "TestFile.doc");
// Set view option.
doc.ViewOptions.ViewType = ViewType.PageLayout;
doc.ViewOptions.ZoomPercent = 50;
dataDir = dataDir + "TestFile.SetZoom_out_.doc";
// Save the finished document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
//Open an existing document
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx");
foreach (StructuredDocumentTag sdt in doc.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
if (sdt.SdtType == SdtType.PlainText)
{
sdt.RemoveAllChildren();
Paragraph para = sdt.AppendChild(new Paragraph(doc)) as Paragraph;
Run run = new Run(doc, "new text goes here");
para.AppendChild(run);
}
else if (sdt.SdtType == SdtType.DropDownList)
{
SdtListItem secondItem = sdt.ListItems[2];
sdt.ListItems.SelectedValue = secondItem;
}
else if (sdt.SdtType == SdtType.Picture)
{
Shape shape = (Shape)sdt.GetChild(NodeType.Shape, 0, true);
if (shape.HasImage)
{
shape.ImageData.SetImage(dataDir + "Watermark.png");
}
}
}
dataDir = dataDir + "ModifyContentControls_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
//Open an existing document
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
//Get the first content control from the document
StructuredDocumentTag SdtCheckBox = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
//StructuredDocumentTag.Checked property gets/sets current state of the Checkbox SDT
if (SdtCheckBox.SdtType == SdtType.Checkbox)
SdtCheckBox.Checked = true;
dataDir = dataDir + "SetCurrentStateOfCheckBox_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify font formatting before adding text.
Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;
builder.Write("Sample text.");
dataDir = dataDir + "WriteAndFont_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
// We will test this functionality creating a document with two fields with date formatting
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert content with German locale.
builder.Font.LocaleId = 1031;
builder.InsertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
builder.Write(" - ");
builder.InsertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");
// Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from.
// Set the culture used during field update to the culture used by the field.
doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode;
doc.MailMerge.Execute(new string[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) });
dataDir = dataDir + "Field.ChangeFieldUpdateCultureSource_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert content with German locale.
builder.Font.LocaleId = 1031;
builder.InsertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\"");
builder.Write(" - ");
builder.InsertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\"");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
// Create a blank document.
Document doc = new Document();
DocumentBuilder b = new DocumentBuilder(doc);
b.InsertField("MERGEFIELD Date");
// Store the current culture so it can be set back once mail merge is complete.
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
// Set to German language so dates and numbers are formatted using this culture during mail merge.
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
// Execute mail merge.
doc.MailMerge.Execute(new string[] { "Date" }, new object[] { DateTime.Now });
// Restore the original culture.
Thread.CurrentThread.CurrentCulture = currentCulture;
doc.Save(dataDir + "Field.ChangeLocale_out_.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Pass the appropriate parameters to convert PAGE fields encountered to static text only in the body of the first section.
FieldsHelper.ConvertFieldsToStaticText(doc.FirstSection.Body, FieldType.FieldPage);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document with fields transformed to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Pass the appropriate parameters to convert all IF fields encountered in the document (including headers and footers) to static text.
FieldsHelper.ConvertFieldsToStaticText(doc, FieldType.FieldIf);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document with fields transformed to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Pass the appropriate parameters to convert all IF fields to static text that are encountered only in the last
// paragraph of the document.
FieldsHelper.ConvertFieldsToStaticText(doc.FirstSection.Body.LastParagraph, FieldType.FieldIf);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document with fields transformed to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class FieldsHelper : DocumentVisitor
{
/// <summary>
/// Converts any fields of the specified type found in the descendants of the node into static text.
/// </summary>
/// <param name="compositeNode">The node in which all descendants of the specified FieldType will be converted to static text.</param>
/// <param name="targetFieldType">The FieldType of the field to convert to static text.</param>
public static void ConvertFieldsToStaticText(CompositeNode compositeNode, FieldType targetFieldType)
{
string originalNodeText = compositeNode.ToString(SaveFormat.Text); //ExSkip
FieldsHelper helper = new FieldsHelper(targetFieldType);
compositeNode.Accept(helper);
Debug.Assert(originalNodeText.Equals(compositeNode.ToString(SaveFormat.Text)), "Error: Text of the node converted differs from the original"); //ExSkip
foreach (Node node in compositeNode.GetChildNodes(NodeType.Any, true)) //ExSkip
Debug.Assert(!(node is FieldChar && ((FieldChar)node).FieldType.Equals(targetFieldType)), "Error: A field node that should be removed still remains."); //ExSkip
}
private FieldsHelper(FieldType targetFieldType)
{
mTargetFieldType = targetFieldType;
}
public override VisitorAction VisitFieldStart(FieldStart fieldStart)
{
// We must keep track of the starts and ends of fields incase of any nested fields.
if (fieldStart.FieldType.Equals(mTargetFieldType))
{
mFieldDepth++;
fieldStart.Remove();
}
else
{
// This removes the field start if it's inside a field that is being converted.
CheckDepthAndRemoveNode(fieldStart);
}
return VisitorAction.Continue;
}
public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
{
// When visiting a field separator we should decrease the depth level.
if (fieldSeparator.FieldType.Equals(mTargetFieldType))
{
mFieldDepth--;
fieldSeparator.Remove();
}
else
{
// This removes the field separator if it's inside a field that is being converted.
CheckDepthAndRemoveNode(fieldSeparator);
}
return VisitorAction.Continue;
}
public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
{
if (fieldEnd.FieldType.Equals(mTargetFieldType))
fieldEnd.Remove();
else
CheckDepthAndRemoveNode(fieldEnd); // This removes the field end if it's inside a field that is being converted.
return VisitorAction.Continue;
}
public override VisitorAction VisitRun(Run run)
{
// Remove the run if it is between the FieldStart and FieldSeparator of the field being converted.
CheckDepthAndRemoveNode(run);
return VisitorAction.Continue;
}
public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
{
if (mFieldDepth > 0)
{
// The field code that is being converted continues onto another paragraph. We
// need to copy the remaining content from this paragraph onto the next paragraph.
Node nextParagraph = paragraph.NextSibling;
// Skip ahead to the next available paragraph.
while (nextParagraph != null && nextParagraph.NodeType != NodeType.Paragraph)
nextParagraph = nextParagraph.NextSibling;
// Copy all of the nodes over. Keep a list of these nodes so we know not to remove them.
while (paragraph.HasChildNodes)
{
mNodesToSkip.Add(paragraph.LastChild);
((Paragraph)nextParagraph).PrependChild(paragraph.LastChild);
}
paragraph.Remove();
}
return VisitorAction.Continue;
}
public override VisitorAction VisitTableStart(Table table)
{
CheckDepthAndRemoveNode(table);
return VisitorAction.Continue;
}
/// <summary>
/// Checks whether the node is inside a field or should be skipped and then removes it if necessary.
/// </summary>
private void CheckDepthAndRemoveNode(Node node)
{
if (mFieldDepth > 0 && !mNodesToSkip.Contains(node))
node.Remove();
}
private int mFieldDepth = 0;
private ArrayList mNodesToSkip = new ArrayList();
private FieldType mTargetFieldType;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "FormFields.doc");
FormFieldCollection documentFormFields = doc.Range.FormFields;
FormField formField1 = documentFormFields[3];
FormField formField2 = documentFormFields["Text2"];
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "FormFields.doc");
FormFieldCollection formFields = doc.Range.FormFields;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "FormFields.doc");
FormField formField = doc.Range.FormFields[3];
if (formField.Type.Equals(FieldType.FieldFormTextInput))
formField.Result = "My name is " + formField.Name;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Shows how to delete all merge fields from a document without executing mail merge.
doc.MailMerge.DeleteFields();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Shows how to get names of all merge fields in a document.
string[] fieldNames = doc.MailMerge.GetFieldNames();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Shows how to add a mapping when a merge field in a document and a data field in a data source have different names.
doc.MailMerge.MappedDataFields.Add("MyFieldName_InDocument", "MyFieldName_InDataSource");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this Advance field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an Advance field like this:
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
// Create instance of FieldAdvance class and lets build the above field code
FieldAdvance field = (FieldAdvance)para.AppendField(FieldType.FieldAdvance, false);
// { ADVANCE \\d 10 " }
field.DownOffset = "10";
// { ADVANCE \\d 10 \\l 10 }
field.LeftOffset = "10";
// { ADVANCE \\d 10 \\l 10 \\r -3.3 }
field.RightOffset = "-3.3";
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 }
field.UpOffset = "0";
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 }
field.HorizontalPosition = "100";
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 }
field.VerticalPosition = "100";
// Finally update this Advance field
field.Update();
dataDir = dataDir + "InsertAdvanceFieldWithOutDocumentBuilder_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this Ask field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an Ask field like this:
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
// Create instance of FieldAsk class and lets build the above field code
FieldAsk field = (FieldAsk)para.AppendField(FieldType.FieldAsk, false);
// { ASK \"Test 1\" " }
field.BookmarkName = "Test 1";
// { ASK \"Test 1\" Test2 }
field.PromptText = "Test2";
// { ASK \"Test 1\" Test2 \\d Test3 }
field.DefaultResponse = "Test3";
// { ASK \"Test 1\" Test2 \\d Test3 \\o }
field.PromptOnceOnMailMerge = true;
// Finally update this Ask field
field.Update();
dataDir = dataDir + "InsertASKFieldWithOutDocumentBuilder_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
// Get paragraph you want to append this AUTHOR field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// We want to insert an AUTHOR field like this:
// { AUTHOR Test1 }
// Create instance of FieldAuthor class and lets build the above field code
FieldAuthor field = (FieldAuthor)para.AppendField(FieldType.FieldAuthor, false);
// { AUTHOR Test1 }
field.AuthorName = "Test1";
// Finally update this AUTHOR field
field.Update();
dataDir = dataDir + "InsertAuthorField_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField(@"MERGEFIELD MyFieldName \* MERGEFORMAT");
dataDir = dataDir + "InsertField_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
string[] items = { "One", "Two", "Three" };
builder.InsertComboBox("DropDown", items, 0);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get paragraph you want to append this merge field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// Move cursor to this paragraph
builder.MoveTo(para);
// We want to insert a mail merge address block like this:
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
// Create instance of FieldAddressBlock class and lets build the above field code
FieldAddressBlock field = (FieldAddressBlock)builder.InsertField(FieldType.FieldAddressBlock, false);
// { ADDRESSBLOCK \\c 1" }
field.IncludeCountryOrRegionName = "1";
// { ADDRESSBLOCK \\c 1 \\d" }
field.FormatAddressOnCountryOrRegion = true;
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 }
field.ExcludedCountryOrRegionName = "Test2";
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 }
field.NameAndAddressFormat = "Test3";
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
field.LanguageId = "Test 4";
// Finally update this merge field
field.Update();
dataDir = dataDir + "InsertMailMergeAddressBlockFieldUsingDOM_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get paragraph you want to append this merge field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// Move cursor to this paragraph
builder.MoveTo(para);
// We want to insert a merge field like this:
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
// Create instance of FieldMergeField class and lets build the above field code
FieldMergeField field = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, false);
// { " MERGEFIELD Test1" }
field.FieldName = "Test1";
// { " MERGEFIELD Test1 \\b Test2" }
field.TextBefore = "Test2";
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 }
field.TextAfter = "Test3";
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m" }
field.IsMapped = true;
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
field.IsVerticalFormatting = true;
// Finally update this merge field
field.Update();
dataDir = dataDir + "InsertMergeFieldUsingDOM_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a few page breaks (just for testing)
for (int i = 0; i < 5; i++)
builder.InsertBreak(BreakType.PageBreak);
// Move the DocumentBuilder cursor into the primary footer.
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
// We want to insert a field like this:
// { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" }
Field field = builder.InsertField(@"IF ");
builder.MoveTo(field.Separator);
builder.InsertField("PAGE");
builder.Write(" <> ");
builder.InsertField("NUMPAGES");
builder.Write(" \"See Next Page\" \"Last Page\" ");
// Finally update the outer field to recalcaluate the final value. Doing this will automatically update
// the inner fields at the same time.
field.Update();
dataDir = dataDir + "InsertNestedFields_out_.docx";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "Field.RemoveField.doc");
Field field = doc.Range.Fields[0];
// Calling this method completely removes the field from the document.
field.Remove();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Represents a facade object for a merge field in a Microsoft Word document.
/// </summary>
internal class MergeField
{
internal MergeField(FieldStart fieldStart)
{
if (fieldStart.Equals(null))
throw new ArgumentNullException("fieldStart");
if (!fieldStart.FieldType.Equals(FieldType.FieldMergeField))
throw new ArgumentException("Field start type must be FieldMergeField.");
mFieldStart = fieldStart;
// Find the field separator node.
mFieldSeparator = fieldStart.GetField().Separator;
if (mFieldSeparator == null)
throw new InvalidOperationException("Cannot find field separator.");
mFieldEnd = fieldStart.GetField().End;
}
/// <summary>
/// Gets or sets the name of the merge field.
/// </summary>
internal string Name
{
get
{
return ((FieldStart)mFieldStart).GetField().Result.Replace("«", "").Replace("»", "");
}
set
{
// Merge field name is stored in the field result which is a Run
// node between field separator and field end.
Run fieldResult = (Run)mFieldSeparator.NextSibling;
fieldResult.Text = string.Format("«{0}»", value);
// But sometimes the field result can consist of more than one run, delete these runs.
RemoveSameParent(fieldResult.NextSibling, mFieldEnd);
UpdateFieldCode(value);
}
}
private void UpdateFieldCode(string fieldName)
{
// Field code is stored in a Run node between field start and field separator.
Run fieldCode = (Run)mFieldStart.NextSibling;
Match match = gRegex.Match(((FieldStart)mFieldStart).GetField().GetFieldCode());
string newFieldCode = string.Format(" {0}{1} ", match.Groups["start"].Value, fieldName);
fieldCode.Text = newFieldCode;
// But sometimes the field code can consist of more than one run, delete these runs.
RemoveSameParent(fieldCode.NextSibling, mFieldSeparator);
}
/// <summary>
/// Removes nodes from start up to but not including the end node.
/// Start and end are assumed to have the same parent.
/// </summary>
private static void RemoveSameParent(Node startNode, Node endNode)
{
if ((endNode != null) && ((Node)startNode.ParentNode != (Node)endNode.ParentNode))
throw new ArgumentException("Start and end nodes are expected to have the same parent.");
Node curChild = startNode;
while ((curChild != null) && (curChild != endNode))
{
Node nextChild = curChild.NextSibling;
curChild.Remove();
curChild = nextChild;
}
}
private readonly Node mFieldStart;
private readonly Node mFieldSeparator;
private readonly Node mFieldEnd;
private static readonly Regex gRegex = new Regex(@"\s*(?<start>MERGEFIELD\s|)(\s|)(?<name>\S+)\s+");
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
// Specify your document name here.
Document doc = new Document(dataDir + "RenameMergeFields.doc");
// Select all field start nodes so we can find the merge fields.
NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);
foreach (FieldStart fieldStart in fieldStarts)
{
if (fieldStart.FieldType.Equals(FieldType.FieldMergeField))
{
MergeField mergeField = new MergeField(fieldStart);
mergeField.Name = mergeField.Name + "_Renamed";
}
}
dataDir = dataDir + "RenameMergeFields_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "Rendering.doc");
// This updates all fields in the document.
doc.UpdateFields();
dataDir = dataDir + "Rendering.UpdateFields_out_.pdf";
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_FindAndReplace();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new ReplaceEvaluatorFindAndHighlight();
// We want the "your document" phrase to be highlighted.
Regex regex = new Regex("your document", RegexOptions.IgnoreCase);
doc.Range.Replace(regex, "", options);
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
private class ReplaceEvaluatorFindAndHighlight : IReplacingCallback
{
/// <summary>
/// This method is called by the Aspose.Words find and replace engine for each match.
/// This method highlights the match string, even if it spans multiple runs.
/// </summary>
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
// This is a Run node that contains either the beginning or the complete match.
Node currentNode = e.MatchNode;
// The first (and may be the only) run can contain text before the match,
// in this case it is necessary to split the run.
if (e.MatchOffset > 0)
currentNode = SplitRun((Run)currentNode, e.MatchOffset);
// This array is used to store all nodes of the match for further highlighting.
ArrayList runs = new ArrayList();
// Find all runs that contain parts of the match string.
int remainingLength = e.Match.Value.Length;
while (
(remainingLength > 0) &&
(currentNode != null) &&
(currentNode.GetText().Length <= remainingLength))
{
runs.Add(currentNode);
remainingLength = remainingLength - currentNode.GetText().Length;
// Select the next Run node.
// Have to loop because there could be other nodes such as BookmarkStart etc.
do
{
currentNode = currentNode.NextSibling;
}
while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
}
// Split the last run that contains the match if there is any text left.
if ((currentNode != null) && (remainingLength > 0))
{
SplitRun((Run)currentNode, remainingLength);
runs.Add(currentNode);
}
// Now highlight all runs in the sequence.
foreach (Run run in runs)
run.Font.HighlightColor = Color.Yellow;
// Signal to the replace engine to do nothing because we have already done all what we wanted.
return ReplaceAction.Skip;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Splits text of the specified run into two runs.
/// Inserts the new run just after the specified run.
/// </summary>
private static Run SplitRun(Run run, int position)
{
Run afterRun = (Run)run.Clone(true);
afterRun.Text = run.Text.Substring(position);
run.Text = run.Text.Substring(0, position);
run.ParentNode.InsertAfter(afterRun, run);
return afterRun;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private class MyReplaceEvaluator : IReplacingCallback
{
/// <summary>
/// This is called during a replace operation each time a match is found.
/// This method appends a number to the match string and returns it as a replacement string.
/// </summary>
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
e.Replacement = e.Match.ToString() + mMatchNumber.ToString();
mMatchNumber++;
return ReplaceAction.Replace;
}
private int mMatchNumber;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_FindAndReplace();
Document doc = new Document(dataDir + "Range.ReplaceWithEvaluator.doc");
FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new MyReplaceEvaluator();
doc.Range.Replace(new Regex("[s|m]ad"), "", options);
dataDir = dataDir + "Range.ReplaceWithEvaluator_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_FindAndReplace();
Document doc = new Document(dataDir + "Document.doc");
FindReplaceOptions options = new FindReplaceOptions();
doc.Range.Replace(new Regex("[s|m]ad"), "bad", options);
dataDir = dataDir + "ReplaceWithRegex_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_FindAndReplace();
string fileName = "Document.doc";
Document doc = new Document(dataDir + fileName);
doc.Range.Replace("sad", "bad", new FindReplaceOptions(FindReplaceDirection.Forward));
dataDir = dataDir + "ReplaceWithString_out_.doc";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
class AddWatermark
{
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithImages();
string fileName = "TestFile.Watermark.doc";
Document doc = new Document(dataDir + fileName);
InsertWatermarkText(doc, "CONFIDENTIAL");
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
doc.Save(dataDir);
Console.WriteLine("\nAdded watermark to the document successfully.\nFile saved at " + dataDir);
}
/// <summary>
/// Inserts a watermark into a document.
/// </summary>
/// <param name="doc">The input document.</param>
/// <param name="watermarkText">Text of the watermark.</param>
private static void InsertWatermarkText(Document doc, string watermarkText)
{
// Create a watermark shape. This will be a WordArt shape.
// You are free to try other shape types as watermarks.
Shape watermark = new Shape(doc, ShapeType.TextPlainText);
// Set up the text of the watermark.
watermark.TextPath.Text = watermarkText;
watermark.TextPath.FontFamily = "Arial";
watermark.Width = 500;
watermark.Height = 100;
// Text will be directed from the bottom-left to the top-right corner.
watermark.Rotation = -40;
// Remove the following two lines if you need a solid black text.
watermark.Fill.Color = Color.Gray; // Try LightGray to get more Word-style watermark
watermark.StrokeColor = Color.Gray; // Try LightGray to get more Word-style watermark
// Place the watermark in the page center.
watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
watermark.WrapType = WrapType.None;
watermark.VerticalAlignment = VerticalAlignment.Center;
watermark.HorizontalAlignment = HorizontalAlignment.Center;
// Create a new paragraph and append the watermark to this paragraph.
Paragraph watermarkPara = new Paragraph(doc);
watermarkPara.AppendChild(watermark);
// Insert the watermark into all headers of each document section.
foreach (Section sect in doc.Sections)
{
// There could be up to three different headers in each section, since we want
// the watermark to appear on all pages, insert into all headers.
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
}
}
private static void InsertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooterType headerType)
{
HeaderFooter header = sect.HeadersFooters[headerType];
if (header == null)
{
// There is no header of the specified type in the current section, create it.
header = new HeaderFooter(sect.Document, headerType);
sect.HeadersFooters.Add(header);
}
// Insert a clone of the watermark into the header.
header.AppendChild(watermarkPara.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_WorkingWithImages();
Document doc = new Document(dataDir + "Image.SampleImages.doc");
NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
int imageIndex = 0;
foreach (Shape shape in shapes)
{
if (shape.HasImage)
{
string imageFileName = string.Format(
"Image.ExportImages.{0}_out_{1}", imageIndex, FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType));
shape.ImageData.Save(dataDir + imageFileName);
imageIndex++;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithImages();
// Create a blank documenet.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// The number of pages the document should have.
int numPages = 4;
// The document starts with one section, insert the barcode into this existing section.
InsertBarcodeIntoFooter(builder, doc.FirstSection, 1, HeaderFooterType.FooterPrimary);
for (int i = 1; i < numPages; i++)
{
// Clone the first section and add it into the end of the document.
Section cloneSection = (Section)doc.FirstSection.Clone(false);
cloneSection.PageSetup.SectionStart = SectionStart.NewPage;
doc.AppendChild(cloneSection);
// Insert the barcode and other information into the footer of the section.
InsertBarcodeIntoFooter(builder, cloneSection, i, HeaderFooterType.FooterPrimary);
}
dataDir = dataDir + "Document_out_.docx";
// Save the document as a PDF to disk. You can also save this directly to a stream.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void InsertBarcodeIntoFooter(DocumentBuilder builder, Section section, int pageId, HeaderFooterType footerType)
{
// Move to the footer type in the specific section.
builder.MoveToSection(section.Document.IndexOf(section));
builder.MoveToHeaderFooter(footerType);
// Insert the barcode, then move to the next line and insert the ID along with the page number.
// Use pageId if you need to insert a different barcode on each page. 0 = First page, 1 = Second page etc.
builder.InsertImage(System.Drawing.Image.FromFile( RunExamples.GetDataDir_WorkingWithImages() + "Barcode1.png"));
builder.Writeln();
builder.Write("1234567890");
builder.InsertField("PAGE");
// Create a right aligned tab at the right margin.
double tabPos = section.PageSetup.PageWidth - section.PageSetup.RightMargin - section.PageSetup.LeftMargin;
builder.CurrentParagraph.ParagraphFormat.TabStops.Add(new TabStop(tabPos, TabAlignment.Right, TabLeader.None));
// Move to the right hand side of the page and insert the page and page total.
builder.Write(ControlChar.Tab);
builder.InsertField("PAGE");
builder.Write(" of ");
builder.InsertField("NUMPAGES");
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
ImportFormatMode mode = ImportFormatMode.KeepSourceFormatting;
// Loop through all sections in the source document.
// Section nodes are immediate children of the Document node so we can just enumerate the Document.
foreach (Section srcSection in srcDoc)
{
// Because we are copying a section from one document to another,
// it is required to import the Section node into the destination document.
// This adjusts any document-specific references to styles, lists, etc.
//
// Importing a node creates a copy of the original node, but the copy
// is ready to be inserted into the destination document.
Node dstSection = dstDoc.ImportNode(srcSection, true, mode);
// Now the new section node can be appended to the destination document.
dstDoc.AppendChild(dstSection);
}
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the joined document
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_JoiningAndAppending();
string fileName = "TestFile.Source.doc";
//ExStart
//ExId:AppendDocument_BaseDocument
//ExSummary:Shows how to remove all content from a document before using it as a base to append documents to.
// Use a blank document as the destination document.
Document dstDoc = new Document();
Document srcDoc = new Document(dataDir + fileName);
// The destination document is not actually empty which often causes a blank page to appear before the appended document
// This is due to the base document having an empty section and the new document being started on the next page.
// Remove all content from the destination document before appending.
dstDoc.RemoveAllChildren();
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Restart the page numbering on the start of the source document.
srcDoc.FirstSection.PageSetup.RestartPageNumbering = true;
srcDoc.FirstSection.PageSetup.PageStartingNumber = 1;
// Append the source document to the end of the destination document.
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
// After joining the documents the NUMPAGE fields will now display the total number of pages which
// is undesired behavior. Call this method to fix them by replacing them with PAGEREF fields.
ConvertNumPageFieldsToPageRef(dstDoc);
// This needs to be called in order to update the new fields with page numbers.
dstDoc.UpdatePageLayout();
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
public static void ConvertNumPageFieldsToPageRef(Document doc)
{
// This is the prefix for each bookmark which signals where page numbering restarts.
// The underscore "_" at the start inserts this bookmark as hidden in MS Word.
const string bookmarkPrefix = "_SubDocumentEnd";
// Field name of the NUMPAGES field.
const string numPagesFieldName = "NUMPAGES";
// Field name of the PAGEREF field.
const string pageRefFieldName = "PAGEREF";
// Create a new DocumentBuilder which is used to insert the bookmarks and replacement fields.
DocumentBuilder builder = new DocumentBuilder(doc);
// Defines the number of page restarts that have been encountered and therefore the number of "sub" documents
// found within this document.
int subDocumentCount = 0;
// Iterate through all sections in the document.
foreach (Section section in doc.Sections)
{
// This section has it's page numbering restarted so we will treat this as the start of a sub document.
// Any PAGENUM fields in this inner document must be converted to special PAGEREF fields to correct numbering.
if (section.PageSetup.RestartPageNumbering)
{
// Don't do anything if this is the first section in the document. This part of the code will insert the bookmark marking
// the end of the previous sub document so therefore it is not applicable for first section in the document.
if (!section.Equals(doc.FirstSection))
{
// Get the previous section and the last node within the body of that section.
Section prevSection = (Section)section.PreviousSibling;
Node lastNode = prevSection.Body.LastChild;
// Use the DocumentBuilder to move to this node and insert the bookmark there.
// This bookmark represents the end of the sub document.
builder.MoveTo(lastNode);
builder.StartBookmark(bookmarkPrefix + subDocumentCount);
builder.EndBookmark(bookmarkPrefix + subDocumentCount);
// Increase the subdocument count to insert the correct bookmarks.
subDocumentCount++;
}
}
// The last section simply needs the ending bookmark to signal that it is the end of the current sub document.
if (section.Equals(doc.LastSection))
{
// Insert the bookmark at the end of the body of the last section.
// Don't increase the count this time as we are just marking the end of the document.
Node lastNode = doc.LastSection.Body.LastChild;
builder.MoveTo(lastNode);
builder.StartBookmark(bookmarkPrefix + subDocumentCount);
builder.EndBookmark(bookmarkPrefix + subDocumentCount);
}
// Iterate through each NUMPAGES field in the section and replace the field with a PAGEREF field referring to the bookmark of the current subdocument
// This bookmark is positioned at the end of the sub document but does not exist yet. It is inserted when a section with restart page numbering or the last
// section is encountered.
Node[] nodes = section.GetChildNodes(NodeType.FieldStart, true).ToArray();
foreach (FieldStart fieldStart in nodes)
{
if (fieldStart.FieldType == FieldType.FieldNumPages)
{
// Get the field code.
string fieldCode = GetFieldCode(fieldStart);
// Since the NUMPAGES field does not take any additional parameters we can assume the remaining part of the field
// code after the fieldname are the switches. We will use these to help recreate the NUMPAGES field as a PAGEREF field.
string fieldSwitches = fieldCode.Replace(numPagesFieldName, "").Trim();
// Inserting the new field directly at the FieldStart node of the original field will cause the new field to
// not pick up the formatting of the original field. To counter this insert the field just before the original field
Node previousNode = fieldStart.PreviousSibling;
// If a previous run cannot be found then we are forced to use the FieldStart node.
if (previousNode == null)
previousNode = fieldStart;
// Insert a PAGEREF field at the same position as the field.
builder.MoveTo(previousNode);
// This will insert a new field with a code like " PAGEREF _SubDocumentEnd0 *\MERGEFORMAT ".
Field newField = builder.InsertField(string.Format(" {0} {1}{2} {3} ", pageRefFieldName, bookmarkPrefix, subDocumentCount, fieldSwitches));
// The field will be inserted before the referenced node. Move the node before the field instead.
previousNode.ParentNode.InsertBefore(previousNode, newField.Start);
// Remove the original NUMPAGES field from the document.
RemoveField(fieldStart);
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void RemoveField(FieldStart fieldStart)
{
Node currentNode = fieldStart;
bool isRemoving = true;
while (currentNode != null && isRemoving)
{
if (currentNode.NodeType == NodeType.FieldEnd)
isRemoving = false;
Node nextNode = currentNode.NextPreOrder(currentNode.Document);
currentNode.Remove();
currentNode = nextNode;
}
}
private static string GetFieldCode(FieldStart fieldStart)
{
StringBuilder builder = new StringBuilder();
for (Node node = fieldStart; node != null && node.NodeType != NodeType.FieldSeparator &&
node.NodeType != NodeType.FieldEnd; node = node.NextPreOrder(node.Document))
{
// Use text only of Run nodes to avoid duplication.
if (node.NodeType == NodeType.Run)
builder.Append(node.GetText());
}
return builder.ToString();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.SourcePageSetup.doc");
// Set the source document to continue straight after the end of the destination document.
// If some page setup settings are different then this may not work and the source document will appear
// on a new page.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous;
// To ensure this does not happen when the source document has different page setup settings make sure the
// settings are identical between the last section of the destination document.
// If there are further continuous sections that follow on in the source document then this will need to be
// repeated for those sections as well.
srcDoc.FirstSection.PageSetup.PageWidth = dstDoc.LastSection.PageSetup.PageWidth;
srcDoc.FirstSection.PageSetup.PageHeight = dstDoc.LastSection.PageSetup.PageHeight;
srcDoc.FirstSection.PageSetup.Orientation = dstDoc.LastSection.PageSetup.Orientation;
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Make the document appear straight after the destination documents content.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous;
// Append the source document using the original styles found in the source document.
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Set the appended document to start on a new page.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
// Append the source document using the original styles found in the source document.
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
// Load the documents to join.
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Keep the formatting from the source document when appending it to the destination document.
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
// Save the joined document to disk.
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_JoiningAndAppending();
string fileName = "TestFile.DestinationList.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Set the source document to appear straight after the destination document's content.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous;
// Iterate through all sections in the source document.
foreach (Paragraph para in srcDoc.GetChildNodes(NodeType.Paragraph, true))
{
para.ParagraphFormat.KeepWithNext = true;
}
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Set the appended document to appear on a new page.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
// Link the headers and footers in the source document to the previous section.
// This will override any headers or footers already found in the source document.
srcDoc.FirstSection.HeadersFooters.LinkToPrevious(true);
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.DestinationList.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.SourceList.doc");
// Append the content of the document so it flows continuously.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous;
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.DestinationList.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.SourceList.doc");
// Set the source document to continue straight after the end of the destination document.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous;
// Keep track of the lists that are created.
Hashtable newLists = new Hashtable();
// Iterate through all paragraphs in the document.
foreach (Paragraph para in srcDoc.GetChildNodes(NodeType.Paragraph, true))
{
if (para.IsListItem)
{
int listId = para.ListFormat.List.ListId;
// Check if the destination document contains a list with this ID already. If it does then this may
// cause the two lists to run together. Create a copy of the list in the source document instead.
if (dstDoc.Lists.GetListByListId(listId) != null)
{
List currentList;
// A newly copied list already exists for this ID, retrieve the stored list and use it on
// the current paragraph.
if (newLists.Contains(listId))
{
currentList = (List)newLists[listId];
}
else
{
// Add a copy of this list to the document and store it for later reference.
currentList = srcDoc.Lists.AddCopy(para.ListFormat.List);
newLists.Add(listId, currentList);
}
// Set the list of this paragraph to the copied list.
para.ListFormat.List = currentList;
}
}
}
// Append the source document to end of the destination document.
dstDoc.AppendDocument(srcDoc, ImportFormatMode.UseDestinationStyles);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the combined document to disk.
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Remove the headers and footers from each of the sections in the source document.
foreach (Section section in srcDoc.Sections)
{
section.ClearHeadersFooters();
}
// Even after the headers and footers are cleared from the source document, the "LinkToPrevious" setting
// for HeadersFooters can still be set. This will cause the headers and footers to continue from the destination
// document. This should set to false to avoid this behavior.
srcDoc.FirstSection.HeadersFooters.LinkToPrevious(false);
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Set the appended document to appear on the next page.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
// Restart the page numbering for the document to be appended.
srcDoc.FirstSection.PageSetup.RestartPageNumbering = true;
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Unlink the headers and footers in the source document to stop this from continuing the headers and footers
// from the destination document.
srcDoc.FirstSection.HeadersFooters.LinkToPrevious(false);
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// If the destination document is rendered to PDF, image etc or UpdatePageLayout is called before the source document
// is appended then any changes made after will not be reflected in the rendered output.
dstDoc.UpdatePageLayout();
// Join the documents.
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
// For the changes to be updated to rendered output, UpdatePageLayout must be called again.
// If not called again the appended document will not appear in the output of the next rendering.
dstDoc.UpdatePageLayout();
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the joined document to PDF.
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_JoiningAndAppending();
string fileName = "TestFile.Destination.doc";
// Load the documents to join.
Document dstDoc = new Document(dataDir + fileName);
Document srcDoc = new Document(dataDir + "TestFile.Source.doc");
// Append the source document using the styles of the destination document.
dstDoc.AppendDocument(srcDoc, ImportFormatMode.UseDestinationStyles);
// Save the joined document to disk.
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
Paragraph para = new Paragraph(doc);
AWords.Section section = doc.LastSection;
section.Body.AppendChild(para);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
Paragraph paragraph = (Paragraph)doc.GetChild(NodeType.Paragraph, 0, true);
NodeCollection children = paragraph.ChildNodes;
foreach (Node child in children)
{
// Paragraph may contain children of various types such as runs, shapes and so on.
if (child.NodeType.Equals(NodeType.Run))
{
// Say we found the node that we want, do something useful.
Run run = (Run)child;
Console.WriteLine(run.Text);
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Create a new empty document. It has one section.
Document doc = new Document();
// The section is the first child node of the document.
Node section = doc.FirstChild;
// The section's parent node is the document.
Console.WriteLine("Section parent is the document: " + (doc == section.ParentNode));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
Paragraph paragraph = (Paragraph)doc.GetChild(NodeType.Paragraph, 0, true);
NodeCollection children = paragraph.ChildNodes;
for (int i = 0; i < children.Count; i++)
{
Node child = children[i];
// Paragraph may contain children of various types such as runs, shapes and so on.
if (child.NodeType.Equals(NodeType.Run))
{
// Say we found the node that we want, do something useful.
Run run = (Run)child;
Console.WriteLine(run.Text);
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Open a file from disk.
Document doc = new Document();
// Creating a new node of any type requires a document passed into the constructor.
Paragraph para = new Paragraph(doc);
// The new paragraph node does not yet have a parent.
Console.WriteLine("Paragraph has no parent node: " + (para.ParentNode == null));
// But the paragraph node knows its document.
Console.WriteLine("Both nodes' documents are the same: " + (para.Document == doc));
// The fact that a node always belongs to a document allows us to access and modify
// properties that reference the document-wide data such as styles or lists.
para.ParagraphFormat.StyleName = "Heading 1";
// Now add the paragraph to the main text of the first section.
doc.FirstSection.Body.AppendChild(para);
// The paragraph node is now a child of the Body node.
Console.WriteLine("Paragraph has a parent node: " + (para.ParentNode != null));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static void RecurseAllNodes()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithNode();
// Open a document.
Document doc = new Document(dataDir + "Node.RecurseAllNodes.doc");
// Invoke the recursive function that will walk the tree.
TraverseAllNodes(doc);
}
/// <summary>
/// A simple function that will walk through all children of a specified node recursively
/// and print the type of each node to the screen.
/// </summary>
public static void TraverseAllNodes(CompositeNode parentNode)
{
// This is the most efficient way to loop through immediate children of a node.
for (Node childNode = parentNode.FirstChild; childNode != null; childNode = childNode.NextSibling)
{
// Do some useful work.
Console.WriteLine(Node.NodeTypeToString(childNode.NodeType));
// Recurse into the node if it is a composite node.
if (childNode.IsComposite)
TraverseAllNodes((CompositeNode)childNode);
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
Section section = doc.FirstSection;
// Quick typed access to the Body child node of the Section.
Body body = section.Body;
// Quick typed access to all Table child nodes contained in the Body.
TableCollection tables = body.Tables;
foreach (Table table in tables)
{
// Quick typed access to the first row of the table.
if (table.FirstRow != null)
table.FirstRow.Remove();
// Quick typed access to the last row of the table.
if (table.LastRow != null)
table.LastRow.Remove();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Returns NodeType.Document
NodeType type = doc.NodeType;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithRanges();
Document doc = new Document(dataDir + "Document.doc");
doc.Sections[0].Range.Delete();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithRanges();
Document doc = new Document(dataDir + "Document.doc");
string text = doc.Range.Text;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir);
Section sectionToAdd = new Section(doc);
doc.Sections.Add(sectionToAdd);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir);
doc.Sections.Clear();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir);
doc.Sections.RemoveAt(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_WorkingWithSections();
Document doc = new Document(dataDir + "Section.AppendContent.doc");
// This is the section that we will append and prepend to.
Section section = doc.Sections[2];
// This copies content of the 1st section and inserts it at the beginning of the specified section.
Section sectionToPrepend = doc.Sections[0];
section.PrependContent(sectionToPrepend);
// This copies content of the 2nd section and inserts it at the end of the specified section.
Section sectionToAppend = doc.Sections[1];
section.AppendContent(sectionToAppend);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithSections();
Document doc = new Document(dataDir + "Document.doc");
Section cloneSection = doc.Sections[0].Clone();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithSections();
Document srcDoc = new Document(dataDir + "Document.doc");
Document dstDoc = new Document();
Section sourceSection = srcDoc.Sections[0];
Section newSection = (Section)dstDoc.ImportNode(sourceSection, true);
dstDoc.Sections.Add(newSection);
dataDir = dataDir + "Document.Copy_out_.doc";
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_WorkingWithSections();
Document doc = new Document(dataDir + "Document.doc");
Section section = doc.Sections[0];
section.ClearHeadersFooters();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithSections();
Document doc = new Document(dataDir + "Document.doc");
Section section = doc.Sections[0];
section.ClearContent();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithSections();
Document doc = new Document(dataDir + "Document.doc");
Section section = doc.Sections[0];
section.PageSetup.LeftMargin = 90; // 3.17 cm
section.PageSetup.RightMargin = 90; // 3.17 cm
section.PageSetup.TopMargin = 72; // 2.54 cm
section.PageSetup.BottomMargin = 72; // 2.54 cm
section.PageSetup.HeaderDistance = 35.4; // 1.25 cm
section.PageSetup.FooterDistance = 35.4; // 1.25 cm
section.PageSetup.TextColumns.Spacing = 35.4; // 1.25 cm
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Retrieve the style used for the first level of the TOC and change the formatting of the style.
doc.Styles[StyleIdentifier.Toc1].Font.Bold = 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_WorkingWithStyles();
string fileName = "Document.TableOfContents.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// Iterate through all paragraphs in the document
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
{
// Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 && para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
{
// Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
TabStop tab = para.ParagraphFormat.TabStops[0];
// Remove the old tab from the collection.
para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
// Insert a new tab using the same properties but at a modified position.
// We could also change the separators used (dots) by passing a different Leader type
para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
}
}
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithStyles();
string fileName = "TestFile.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
// Define style names as they are specified in the Word document.
const string paraStyle = "Heading 1";
const string runStyle = "Intense Emphasis";
// Collect paragraphs with defined styles.
// Show the number of collected paragraphs and display the text of this paragraphs.
ArrayList paragraphs = ParagraphsByStyleName(doc, paraStyle);
Console.WriteLine(string.Format("Paragraphs with \"{0}\" styles ({1}):", paraStyle, paragraphs.Count));
foreach (Paragraph paragraph in paragraphs)
Console.Write(paragraph.ToString(SaveFormat.Text));
// Collect runs with defined styles.
// Show the number of collected runs and display the text of this runs.
ArrayList runs = RunsByStyleName(doc, runStyle);
Console.WriteLine(string.Format("\nRuns with \"{0}\" styles ({1}):", runStyle, runs.Count));
foreach (Run run in runs)
Console.WriteLine(run.Range.Text);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static ArrayList ParagraphsByStyleName(Document doc, string styleName)
{
// Create an array to collect paragraphs of the specified style.
ArrayList paragraphsWithStyle = new ArrayList();
// Get all paragraphs from the document.
NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);
// Look through all paragraphs to find those with the specified style.
foreach (Paragraph paragraph in paragraphs)
{
if (paragraph.ParagraphFormat.Style.Name == styleName)
paragraphsWithStyle.Add(paragraph);
}
return paragraphsWithStyle;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public static ArrayList RunsByStyleName(Document doc, string styleName)
{
// Create an array to collect runs of the specified style.
ArrayList runsWithStyle = new ArrayList();
// Get all runs from the document.
NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);
// Look through all runs to find those with the specified style.
foreach (Run run in runs)
{
if (run.Font.Style.Name == styleName)
runsWithStyle.Add(run);
}
return runsWithStyle;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Represents a facade object for a column of a table in a Microsoft Word document.
/// </summary>
internal class Column
{
private Column(Table table, int columnIndex)
{
if (table == null)
throw new ArgumentException("table");
mTable = table;
mColumnIndex = columnIndex;
}
/// <summary>
/// Returns a new column facade from the table and supplied zero-based index.
/// </summary>
public static Column FromIndex(Table table, int columnIndex)
{
return new Column(table, columnIndex);
}
/// <summary>
/// Returns the cells which make up the column.
/// </summary>
public Cell[] Cells
{
get
{
return (Cell[])GetColumnCells().ToArray(typeof(Cell));
}
}
/// <summary>
/// Returns the index of the given cell in the column.
/// </summary>
public int IndexOf(Cell cell)
{
return GetColumnCells().IndexOf(cell);
}
/// <summary>
/// Inserts a brand new column before this column into the table.
/// </summary>
public Column InsertColumnBefore()
{
Cell[] columnCells = Cells;
if (columnCells.Length == 0)
throw new ArgumentException("Column must not be empty");
// Create a clone of this column.
foreach (Cell cell in columnCells)
cell.ParentRow.InsertBefore(cell.Clone(false), cell);
// This is the new column.
Column column = new Column(columnCells[0].ParentRow.ParentTable, mColumnIndex);
// We want to make sure that the cells are all valid to work with (have at least one paragraph).
foreach (Cell cell in column.Cells)
cell.EnsureMinimum();
// Increase the index which this column represents since there is now one extra column infront.
mColumnIndex++;
return column;
}
/// <summary>
/// Removes the column from the table.
/// </summary>
public void Remove()
{
foreach (Cell cell in Cells)
cell.Remove();
}
/// <summary>
/// Returns the text of the column.
/// </summary>
public string ToTxt()
{
StringBuilder builder = new StringBuilder();
foreach (Cell cell in Cells)
builder.Append(cell.ToString(SaveFormat.Text));
return builder.ToString();
}
/// <summary>
/// Provides an up-to-date collection of cells which make up the column represented by this facade.
/// </summary>
private ArrayList GetColumnCells()
{
ArrayList columnCells = new ArrayList();
foreach (Row row in mTable.Rows)
{
Cell cell = row.Cells[mColumnIndex];
if (cell != null)
columnCells.Add(cell);
}
return columnCells;
}
private int mColumnIndex;
private Table mTable;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Get the second column in the table.
Column column = Column.FromIndex(table, 0);
// Print the plain text of the column to the screen.
Console.WriteLine(column.ToTxt());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Get the first table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Get the second column in the table.
Column column = Column.FromIndex(table, 0);
// Print the plain text of the column to the screen.
Console.WriteLine(column.ToTxt());
// Create a new column to the left of this column.
// This is the same as using the "Insert Column Before" command in Microsoft Word.
Column newColumn = column.InsertColumnBefore();
// Add some text to each of the column cells.
foreach (Cell cell in newColumn.Cells)
cell.FirstParagraph.AppendChild(new Run(doc, "Column Text " + newColumn.IndexOf(cell)));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Get the second table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 1, true);
// Get the third column from the table and remove it.
Column column = Column.FromIndex(table, 2);
column.Remove();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Table.EmptyTable.doc");
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Align the table to the center of the page.
table.Alignment = TableAlignment.Center;
// Clear any existing borders from the table.
table.ClearBorders();
// Set a green border around the table but not inside.
table.SetBorder(BorderType.Left, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Right, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Top, LineStyle.Single, 1.5, Color.Green, true);
table.SetBorder(BorderType.Bottom, LineStyle.Single, 1.5, Color.Green, true);
// Fill the cells with a light green solid color.
table.SetShading(TextureIndex.TextureSolid, Color.LightGreen, Color.Empty);
dataDir = dataDir + "Table.SetOutlineBorders_out_.doc";
// Save the document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
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 + "Table.ApplyRowFormatting_out_.doc";
// Save the document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Table.EmptyTable.doc");
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Clear any existing borders from the table.
table.ClearBorders();
// Set a green border around and inside the table.
table.SetBorders(LineStyle.Single, 1.5, Color.Green);
dataDir = dataDir + "Table.SetAllBorders_out_.doc";
// Save the document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
builder.InsertCell();
// Set the borders for the entire table.
table.SetBorders(LineStyle.Single, 2.0, Color.Black);
// Set the cell shading for this cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
builder.Writeln("Cell #1");
builder.InsertCell();
// Specify a different cell shading for the second cell.
builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
builder.Writeln("Cell #2");
// End this row.
builder.EndRow();
// Clear the cell formatting from previous operations.
builder.CellFormat.ClearFormatting();
// Create the second row.
builder.InsertCell();
// Create larger borders for the first cell of this row. This will be different.
// compared to the borders set for the table.
builder.CellFormat.Borders.Left.LineWidth = 4.0;
builder.CellFormat.Borders.Right.LineWidth = 4.0;
builder.CellFormat.Borders.Top.LineWidth = 4.0;
builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
builder.Writeln("Cell #3");
builder.InsertCell();
// Clear the cell formatting from the previous cell.
builder.CellFormat.ClearFormatting();
builder.Writeln("Cell #4");
// Save finished document.
doc.Save(dataDir + "Table.SetBordersAndShading_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 + "Table.Document.doc");
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Retrieve the first cell in the table.
Cell firstCell = table.FirstRow.FirstCell;
// Modify some cell level properties.
firstCell.CellFormat.Width = 30; // in points
firstCell.CellFormat.Orientation = TextOrientation.Downward;
firstCell.CellFormat.Shading.ForegroundPatternColor = Color.LightGreen;
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Table.Document.doc");
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Retrieve the first row in the table.
Row firstRow = table.FirstRow;
// Modify some row level properties.
firstRow.RowFormat.Borders.LineStyle = LineStyle.None;
firstRow.RowFormat.HeightRule = HeightRule.Auto;
firstRow.RowFormat.AllowBreakAcrossPages = true;
// 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();
// We must insert at least one row first before setting any table formatting.
builder.InsertCell();
// Set the table style used based of the unique style identifier.
// Note that not all table styles are available when saving as .doc format.
table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1;
// Apply which features should be formatted by the style.
table.StyleOptions = TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow;
table.AutoFit(AutoFitBehavior.AutoFitToContents);
// Continue with building the table as normal.
builder.Writeln("Item");
builder.CellFormat.RightPadding = 40;
builder.InsertCell();
builder.Writeln("Quantity (kg)");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Apples");
builder.InsertCell();
builder.Writeln("20");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Bananas");
builder.InsertCell();
builder.Writeln("40");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Carrots");
builder.InsertCell();
builder.Writeln("50");
builder.EndRow();
dataDir = dataDir + "DocumentBuilder.SetTableStyle_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
Document doc = new Document(dataDir + "Table.TableStyle.docx");
// Get the first cell of the first table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
Cell firstCell = table.FirstRow.FirstCell;
// First print the color of the cell shading. This should be empty as the current shading
// is stored in the table style.
Color cellShadingBefore = firstCell.CellFormat.Shading.BackgroundPatternColor;
Console.WriteLine("Cell shading before style expansion: " + cellShadingBefore.ToString());
// Expand table style formatting to direct formatting.
doc.ExpandTableStylesToDirectFormatting();
// Now print the cell shading after expanding table styles. A blue background pattern color
// should have been applied from the table style.
Color cellShadingAfter = firstCell.CellFormat.Shading.BackgroundPatternColor;
Console.WriteLine("Cell shading after style expansion: " + cellShadingAfter.ToString());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithTables();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Auto fit the table to the cell contents
table.AutoFit(AutoFitBehavior.AutoFitToContents);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document to disk.
doc.Save(dataDir);
Debug.Assert(doc.FirstSection.Body.Tables[0].PreferredWidth.Type == PreferredWidthType.Auto, "PreferredWidth type is not auto");
Debug.Assert(doc.FirstSection.Body.Tables[0].FirstRow.FirstCell.CellFormat.PreferredWidth.Type == PreferredWidthType.Auto, "PrefferedWidth on cell is not auto");
Debug.Assert(doc.FirstSection.Body.Tables[0].FirstRow.FirstCell.CellFormat.PreferredWidth.Value == 0, "PreferredWidth value is not 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_WorkingWithTables();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Disable autofitting on this table.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document to disk.
doc.Save(dataDir);
//ExEnd
Debug.Assert(doc.FirstSection.Body.Tables[0].PreferredWidth.Type == PreferredWidthType.Auto, "PreferredWidth type is not auto");
Debug.Assert(doc.FirstSection.Body.Tables[0].PreferredWidth.Value == 0, "PreferredWidth value is not 0");
Debug.Assert(doc.FirstSection.Body.Tables[0].FirstRow.FirstCell.CellFormat.Width == 69.2, "Cell width is not correct.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithTables();
string fileName = "TestFile.doc";
// Open the document
Document doc = new Document(dataDir + fileName);
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Autofit the first table to the page width.
table.AutoFit(AutoFitBehavior.AutoFitToWindow);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the document to disk.
doc.Save(dataDir);
Debug.Assert(doc.FirstSection.Body.Tables[0].PreferredWidth.Type == PreferredWidthType.Percent, "PreferredWidth type is not percent");
Debug.Assert(doc.FirstSection.Body.Tables[0].PreferredWidth.Value == 100, "PreferredWidth value is different than 100");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Table.SimpleTable.doc");
// Retrieve the first table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Create a clone of the table.
Table tableClone = (Table)table.Clone(true);
// Insert the cloned table into the document after the original
table.ParentNode.InsertAfter(tableClone, table);
// Insert an empty paragraph between the two tables or else they will be combined into one
// upon save. This has to do with document validation.
table.ParentNode.InsertAfter(new Paragraph(doc), table);
dataDir = dataDir + "Table.CloneTableAndInsert_out_.doc";
// Save the document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir + "Table.SimpleTable.doc");
// Retrieve the first table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Clone the last row in the table.
Row clonedRow = (Row)table.LastRow.Clone(true);
// Remove all content from the cloned row's cells. This makes the row ready for
// new content to be inserted into.
foreach (Cell cell in clonedRow.Cells)
cell.RemoveAllChildren();
// Add the row to the end of the table.
table.AppendChild(clonedRow);
dataDir = dataDir + "Table.AddCloneRowToTable_out_.doc";
// Save the document to disk.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir);
// Get the first table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// The range text will include control characters such as "\a" for a cell.
// You can call ToString and pass SaveFormat.Text on the desired node to find the plain text content.
// Print the plain text range of the table to the screen.
Console.WriteLine("Contents of the table: ");
Console.WriteLine(table.Range.Text);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Print the contents of the second row to the screen.
Console.WriteLine("\nContents of the row: ");
Console.WriteLine(table.Rows[1].Range.Text);
// Print the contents of the last cell in the table to the screen.
Console.WriteLine("\nContents of the cell: ");
Console.WriteLine(table.LastRow.LastCell.Range.Text);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(dataDir);
// Get the first table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
// Replace any instances of our string in the entire table.
table.Range.Replace("Carrots", "Eggs", new FindReplaceOptions(FindReplaceDirection.Forward));
// Replace any instances of our string in the last cell of the table only.
table.LastRow.LastCell.Range.Replace("50", "20", new FindReplaceOptions(FindReplaceDirection.Forward));
dataDir = RunExamples.GetDataDir_WorkingWithTables() + "Table.ReplaceCellText_out_.doc";
doc.Save(dataDir);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment