Search code examples
c#replacesyncfusionmergefield

Syncfusion DocIO Replace Text with merge Field


I have a whole bunch of document which have a plain text place marker like ~{fieldToBeReplaced} and I want it to be replaced with a Merge field.

I have the following code which kind of inserts the merge field and then inserts the text << MERGEFIELD_NAME >>.

What I want is it to be the mergefield with the name displayed just like it would be if i were to Insert->Merge Field in word.


void Main()
{
    Console.WriteLine(":::::  Replacing BookMarks  ::::: ");
    //Search And Replace bookmarks
    try
    {
        var replaceDir = new DirectoryInfo(saveFileLocation);
        var bookmarkFiles = replaceDir.GetFiles().ToList();
        foreach (var bkmFile in bookmarkFiles)
        {
            if (SearchReplaceBookmarks(bkmFile.FullName))
            {
                Console.WriteLine("Bookmarks Replace:" + bkmFile.Name + " ::: ");
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERROR: ::: " + ex.Message);
    }
}

static string startDir = Path.GetDirectoryName(Util.CurrentQueryPath);
string saveFileLocation = startDir + @"\Converted\";

private List<fieldReplace> fieldList = new List<fieldReplace>() {
    //new fieldReplace("",""),
    new fieldReplace("~{U-nm}","_Doctor"),
    new fieldReplace("~{P-nl}","_Patient_Surname","Patient_Firstname"),
    new fieldReplace("~{DOBN}","_Patient_DOB"),
    new fieldReplace("~{U-ph","_Doctor_PhoneWork"),
    new fieldReplace("~{U-pm}","_Doctor_PhoneMobile")
}

private bool SearchReplaceBookmarks(string filename)
{
    try
    {
        WordDocument wordDocument = new WordDocument(filename);
        
        foreach (var fld in fieldList)
        {
            var replaceBookmark = wordDocument.Find(fld.TextToReplace, false, true);
            //if the bookmark is in the list then
            while (replaceBookmark != null)
            {
                //Find and replace text with merge field.
                var paragraph = new WParagraph(wordDocument);
                for (int i =0 ; i<= fld.FieldNames.Length-1;i++){
                    var field = paragraph.AppendField(fld.FieldNames[i], FieldType.FieldMergeField);
                    field.FieldType = FieldType.FieldMergeField;
                    if (i < fld.FieldNames.Length - 1) { paragraph.AppendText(", ");}
                }
                var selection = new TextSelection(paragraph, 0, paragraph.Text.Length);
                
                //This is where the Merge Field is meant to be inserted
                wordDocument.Replace(fld.TextToReplace, selection, true, true);  
                replaceBookmark = wordDocument.FindNext(paragraph, fld.TextToReplace, false, true);
            }
        }
        //Debug.Write( wordDocument.MailMerge.MappedFields);
        wordDocument.Save(filename, FormatType.Docx);
        wordDocument.Close();
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine("ERROR:" + filename + " ::: " + ex.Message);
        return false;
    }
}

private class fieldReplace
{
    public fieldReplace(string oldText, params string[] newNewFieldName)
    {
        this.TextToReplace = oldText;
        this.FieldNames = newNewFieldName;
    }
    public string TextToReplace { get; set; }
    public string[] FieldNames { get; set; }
}


Solution

  • On analyzing on your mentioned scenario, 1) Finding the place holder text from the Word document. 2) Replacing the place holder text with the merge fields and the fields to be replaced as such in MS Word document.

    Yes, using DocIO the place holder text can be replaced with merge fields as equivalent to MS Word. We have modified your code to achieve your requirement. We have used TextBodyPart overload of the Replace() method. Please find the below code snippet.

    Modified Code Snippet TextBodyPart bodyPart = new TextBodyPart(wordDocument); bodyPart.BodyItems.Add(paragraph); wordDocument.Replace(fld.TextToReplace, bodyPart, true, true);

    For further questions please contact our support team at support@syncfusion.com to get a prompt assistance on this.