Search code examples
mailmergeaspose.words

Error! Unknown op code for conditional


I am using Aspose.Words to do the MailMerge. But after merge for a merge field, It is showing Error! Unknown op code for conditional in document itself. This error may be due to incorrectly formed merged field. But my requirement is to detect/catch such error through code. Because, in our case user themselves creates the word template and upload into system. I have written very simple code to read do the mail merge.

doc.MailMerge.Execute(this.DataSource.Rows[rowIndex];

Can we detect such error in code? I tried to find online, but nothing useful could find.


Solution

  • No exception will be thrown in this scenario, but you can catch using the result of field after merging. Try the below sample code

    // Load the document
    Aspose.Words.Document doc = new Aspose.Words.Document(src);
    // Do processing and mail merge etc
    
    // Select all field start nodes so we can find the merge fields.
    NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);
    foreach (FieldStart fieldStart in fieldStarts)
    {
        // Get the next sibling
        Run fieldResult = (Run)fieldStart.NextSibling;
    
        // Match the error code with the result
        if (fieldResult.NextSibling.NextSibling.GetText().Equals("Error! Unknown op code for conditional.", StringComparison.CurrentCultureIgnoreCase))
        {
            // Find the page number, where the field is present
            LayoutCollector collector = new LayoutCollector(doc);
            int pageNumber = collector.GetStartPageIndex(fieldStart);
            Console.WriteLine("Error in field at Page: " + pageNumber + ". Field text: " + fieldResult.GetText());
        }
    }