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

Free Support Forum - aspose.com

Content Controls and Binding Example?

I would like to programmatically generate a word document, binding a set of content controls to an IEnumerable (or some other kind of collection). I have not found any example of this, but in the marketing materials it appears to be possible. Lots of posts for people asking, but nothing concrete. Can anyone please direct me to any kind of documentation / examples of how I can enumerate a collection / data table / etc. and populate a word document with matching content controls?


Thanks,
Sherri

Update: I just tried using mail merge functionality, but it appears that the value that is returned from IMailMergeDataSource.GetValue is ToString()'d, as the document just has “Aspose.Words.Markup.StructuredDocumentTag” in place of where I returned the value.

Hi Sherri,


Thanks for your inquiry. I believe, you can meet this requirement using mail merge functionality of Aspose.Words. If you find any issues, please attach your sample input template document and expected output document here for testing. Please create expected document using MS Word. We will investigate the issue on our end and provide you more information.

Best regards,

Thank you for your response. When doing a mail merge do we have the ability to inject Content Controls? I thought that whatever IMailMergeDataSource.GetValue returned was converted to a string? Is is possible to return a StructuredDocumentTag?


Thank you,
Sherri

Hi Sherri,


Thanks for your inquiry. You can simulate the desired output by implementing IFieldMergingCallback interface. Please find attached sample template document and here is sample code:

Document doc = new Document(MyDir + @“input.docx”);

doc.MailMerge.FieldMergingCallback = new HandleMergeField();

doc.MailMerge.Execute(new string[] { "mf" }, new object[] { "this should be inside SDT" });

doc.Save(MyDir + @"15.9.0.docx");


private class HandleMergeField : IFieldMergingCallback

{

///

/// This handler is called for every mail merge field found in the document,

/// for every record found in the data source.

///

void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)

{

// We decided that we want all values to be output as SDT content control.

StructuredDocumentTag sdt = new StructuredDocumentTag(e.Document, SdtType.PlainText, MarkupLevel.Inline);

((Run)sdt.FirstChild).Text = e.FieldValue.ToString();

// Get actual merge field

FieldMergeField mergeField = (FieldMergeField)e.Field;

// Insert SDT before this merge field

mergeField.Start.ParentNode.InsertBefore(sdt, mergeField.Start);

//Remove merge field

mergeField.Remove();

}

void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)

{

// Do nothing.

}

}

Hope, this helps.

Best regards,