Inserting New MergeFields

Hi There,

I am currently working on a solution using your ASPOSE.WORDS solution. I have been given 100+ Word Templates with non standard merge tags from a legacy solution.

These merge tags are in the format <* tagname <em>>.

I would like to convert all these non standard tags into proper Word MailMerge fields, but I am not sure where to start. Is it possible to search and replace normal text with the special MailMerge fields using your WORDS solution?

To simplify my problem … can I change instances of the following plain text:

<</em> tagname *>

with the special control

{ MERGEFIELD tagname * MERGEFORMAT }

in such away the new document will work with MailMerge?

Regards,

Laurie Keith

Hi Laurie,

Please try the following code. I have tested it on several sample documents and it seems to do the job:

private void InsertNewMergeFields()
{
    // template filename
    string filename1 = Application.StartupPath + @"\testInsertNewMergeFields.doc";
    // resulting filename
    string filename2 = Application.StartupPath + @"\testInsertNewMergeFields Out.doc";
    Document doc = new Document(filename1);
    insertFieldBuilder = new DocumentBuilder(doc);
    string pattern = @"<\* (?\w+) \*>";
    Regex regex = new Regex(pattern, RegexOptions.Compiled);
    foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
    {
        para.Range.Replace(new Regex(pattern), new ReplaceEvaluator(InsertFieldEvaluator), false);
    }
    // Save resulting document.
    doc.Save(filename2);
    // Open saved document in MS Word to check results.
    System.Diagnostics.Process.Start(filename2);
}
DocumentBuilder insertFieldBuilder;

private ReplaceAction InsertFieldEvaluator(object sender, ReplaceEvaluatorArgs e)
{
    string mark = "\xbf";
    Paragraph para = (Paragraph)e.MatchNode.ParentNode;
    para.Range.Replace(e.Match.Value, mark, true, false);
    string name = e.Match.Groups[1].Value;
    foreach (Run run in para.Runs)
    {
        int pos;
        while ((pos = run.Text.IndexOf(mark)) >= 0)
        {
            // make the separate run containing the text before the searched string
            Run prependedRun = (Run)run.Clone(false);
            // make the initial run to contain only the text that is after the searched string
            prependedRun.Text = prependedRun.Text.Substring(0, pos);
            run.Text = run.Text.Substring(pos + 1, run.Text.Length - pos - 1);
            para.ChildNodes.Insert(para.ChildNodes.IndexOf(run), prependedRun);
            insertFieldBuilder.MoveTo(run);
            insertFieldBuilder.InsertField(@"MERGEFIELD " + name + @" \* MERGEFORMAT", "«" + name + "»");
        }
    }
    return ReplaceAction.Skip;
}

Please don’t hesitate to ask if you have more questions.

Best regards,