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

Free Support Forum - aspose.com

Extract Content Control, Merge Field Names & Replace with Values & Convert Word DOC Stream to PDF using C# .NET

I’d like to know if Aspose can help in these areas:

  1. Extract from Word documents the control names, mergedfield names etc… (screenshot below)
  2. Replace controls, mergedfields etc. with values
  3. Convert the finished Word doc to PDF format

All of this needs to be performed in a stream (Memory or File). Can Aspose help?

controls.png (24.6 KB)

@hsiungst,

Please see these sample input and output DOCX / PDF files and try running the following C# code of Aspose.Words for .NET API:

C# Code:

Document doc = new Document("C:\\Temp\\in.docx");

// Extract from Word documents the merged field names 
foreach (string mergeFieldName in doc.MailMerge.GetFieldNames())
    Console.WriteLine(mergeFieldName);
            
// Extract from Word documents the content control names
foreach (StructuredDocumentTag contentControl in doc.GetChildNodes(NodeType.StructuredDocumentTag, true))
    Console.WriteLine(contentControl.Tag); // contentControl.Title

// Replace merged fields with values
doc.MailMerge.Execute(new string[] { "mf1", "mf2" }, new object[] { "merge Field value 1", "merge Field value 2" });

// Replace plain text content controls with values
foreach (StructuredDocumentTag contentControl in doc.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
    if (contentControl.SdtType == SdtType.PlainText)
    {
        contentControl.RemoveAllChildren();
        contentControl.AppendChild(new Run(doc, "new value for content Control"));
    }
}

// Save final output to DOCX and PDF format
doc.Save("C:\\Temp\\20.8.docx");
doc.Save("C:\\Temp\\20.8.pdf");

Please also refer to following sections of documentation:

Thanks … do I have to remove controls before I populate it? or can I just write some text to the text control? I’m hoping to target controls by tag/field names. Also, can this all work in memory stream or some kind of stream?
Something like this:
if(control1.Name == ??)
control1.Value = “XXX”

if (contentControl.SdtType == SdtType.PlainText)
{
contentControl.RemoveAllChildren();
contentControl.AppendChild(new Run(doc, “new value for content Control”));
}

@hsiungst,

You can either first remove all content from Control and then insert new text in it or keep existing content and append new text at the end of Control. Also, you can perform these tasks by using streams (e.g. MemoryStream or byte[]).