We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Create new document for each nested region


I am currently using the nested regions in the mail merge to great effect. However the client that I am working with has requested that a new document be generated for each parent item.

For example if I had a table customer and a child table orders. The customer would like a new document for each customer with a region in it for displaying the orders. Is this possible? I am using XML to generate a related DataSet in C#

This message was posted using Aspose.Live 2 Forum

Hi there,

Thanks for your inquiry.

Sure, please use the code below to achieve what you are looking for. You simply pass the name of the parent region e.g Customer and then execute mail merge.

Document doc = new Document("Document.doc");<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

MailMergeMultipleDocuments mergeHandler = new MailMergeMultipleDocuments("ParentTable");

doc.MailMerge.FieldMergingCallback = mergeHandler;


// This extra call is required because there is no way to know from within the handler if the

// merge has finished. This means the last region will not be processed without this extra call.


public class MailMergeMultipleDocuments : IFieldMergingCallback


private string mOuterRegionName;

private int currentIndex = -1;

private Paragraph startPara;

private Paragraph endPara;

public MailMergeMultipleDocuments(string tableName)


mOuterRegionName = tableName;


public void FieldMerging(FieldMergingArgs args)


if (args.TableName == mOuterRegionName && args.RecordIndex != currentIndex)


if (args.RecordIndex > 0)




startPara = args.Field.Start.ParentParagraph;

currentIndex = args.RecordIndex;




endPara = args.Field.Start.ParentParagraph;




/// Produces a new document from the currently merged region using the start and end

/// pargraph markers.


public void CreateNewDocumentFromCurrentRegion()


Document dstDoc = (Document)startPara.Document.Clone(false);



Node currNode = startPara;

bool isExtracting = true;

while (isExtracting)


Node dstNode = dstDoc.ImportNode(currNode, true, ImportFormatMode.UseDestinationStyles);


if (currNode.Equals(endPara))

isExtracting = false;

currNode = currNode.NextSibling;


dstDoc.Save(string.Format("Document Out {0}.doc", currentIndex));


public void ImageFieldMerging(ImageFieldMergingArgs args)


// Do Nothing



If you have any troubles please feel free to ask.