IReplacingCallback Interface

Implement this interface if you want to have your own custom method called during a find and replace operation.

Namespace:  Aspose.Words.Replacing
Assembly:  Aspose.Words (in Aspose.Words.dll) Version: 20.9.0

Syntax

public interface IReplacingCallback

The IReplacingCallback type exposes the following members.

Methods

  NameDescription
Public methodCode exampleReplacing
A user defined method that is called during a replace operation for each match found just before a replace is made.

Examples

Replaces text specified with regular expression with HTML.
public void ReplaceWithInsertHtml()
{
    // Open the document
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    builder.Writeln("Hello <CustomerName>,");

    FindReplaceOptions options = new FindReplaceOptions();
    options.ReplacingCallback = new ReplaceWithHtmlEvaluator();

    doc.Range.Replace(new Regex(@" <CustomerName>,"), string.Empty, options);

    // Save the modified document
    doc.Save(ArtifactsDir + "Range.ReplaceWithInsertHtml.docx");
    Assert.AreEqual("James Bond, Hello\r\x000c",
}

private class ReplaceWithHtmlEvaluator : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
        builder.MoveTo(args.MatchNode);

        // Replace '<CustomerName>' text with a red bold name
        builder.InsertHtml("<b><font color='red'>James Bond, </font></b>");
        args.Replacement = "";

        return ReplaceAction.Replace;
    }
}
Show changes for headers and footers order.
public void HeaderFooterOrder()
        {
            Document doc = new Document(MyDir + "Header and footer types.docx");

            // Assert that we use special header and footer for the first page
            // The order for this: first header\footer, even header\footer, primary header\footer
            Section firstPageSection = doc.FirstSection;
            Assert.AreEqual(true, firstPageSection.PageSetup.DifferentFirstPageHeaderFooter);

            ReplaceLog logger = new ReplaceLog();
            FindReplaceOptions options = new FindReplaceOptions { ReplacingCallback = logger };
            doc.Range.Replace(new Regex("(header|footer)"), "", options);

            doc.Save(ArtifactsDir + "HeaderFooter.HeaderFooterOrder.docx");

#if NET462 || NETCOREAPP2_1 || JAVA
            Assert.AreEqual("First header\nFirst footer\nSecond header\nSecond footer\nThird header\n" +
                "Third footer\n", logger.Text.Replace("\r", ""));
#elif NETCOREAPP2_1 || __MOBILE__
            Assert.AreEqual("First header\nFirst footer\nSecond header\nSecond footer\nThird header\n" +
                "Third footer\n", logger.Text);
#endif

            // Prepare our string builder for assert results without "DifferentFirstPageHeaderFooter"
            logger.ClearText();

            // Remove special first page
            // The order for this: primary header, default header, primary footer, default footer, even header\footer
            firstPageSection.PageSetup.DifferentFirstPageHeaderFooter = false;
            doc.Range.Replace(new Regex("(header|footer)"), "", options);

#if NET462 || NETCOREAPP2_1 || JAVA
            Assert.AreEqual("Third header\nFirst header\nThird footer\nFirst footer\nSecond header\n" +
                "Second footer\n", logger.Text.Replace("\r", ""));
#elif NETCOREAPP2_1 || __MOBILE__
            Assert.AreEqual("Third header\nFirst header\nThird footer\nFirst footer\nSecond header\n" +
                "Second footer\n", logger.Text);
#endif
        }

        private class ReplaceLog : IReplacingCallback
        {
            public ReplaceAction Replacing(ReplacingArgs args)
            {
                mTextBuilder.AppendLine(args.MatchNode.GetText());
                return ReplaceAction.Skip;
            }

            internal void ClearText()
            {
                mTextBuilder.Clear();
            }

            internal string Text => mTextBuilder.ToString();

            private readonly StringBuilder mTextBuilder = new StringBuilder();
        }
Shows how to insert content of one document into another during a customized find and replace operation.
public void InsertDocumentAtReplace()
{
    Document mainDoc = new Document(MyDir + "Document insertion destination.docx");

    FindReplaceOptions options = new FindReplaceOptions();
    options.Direction = FindReplaceDirection.Backward;
    options.ReplacingCallback = new InsertDocumentAtReplaceHandler();

    mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
    mainDoc.Save(ArtifactsDir + "InsertDocument.InsertDocumentAtReplace.docx");

}

private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
    {
        Document subDoc = new Document(MyDir + "Document.docx");

        // Insert a document after the paragraph, containing the match text
        Paragraph para = (Paragraph)args.MatchNode.ParentNode;
        InsertDocument(para, subDoc);

        // Remove the paragraph with the match text
        para.Remove();

        return ReplaceAction.Skip;
    }
}

/// <summary>
/// Inserts content of the external document after the specified node.
/// </summary>
static void InsertDocument(Node insertionDestination, Document docToInsert)
{
    // Make sure that the node is either a paragraph or table
    if (insertionDestination.NodeType.Equals(NodeType.Paragraph) || insertionDestination.NodeType.Equals(NodeType.Table))
    {
        // We will be inserting into the parent of the destination paragraph
        CompositeNode dstStory = insertionDestination.ParentNode;

        // This object will be translating styles and lists during the import
        NodeImporter importer =
            new NodeImporter(docToInsert, insertionDestination.Document, ImportFormatMode.KeepSourceFormatting);

        // Loop through all block level nodes in the body of the section
        foreach (Section srcSection in docToInsert.Sections.OfType<Section>())
            foreach (Node srcNode in srcSection.Body)
            {
                // Skip the node if it is a last empty paragraph in a section
                if (srcNode.NodeType.Equals(NodeType.Paragraph))
                {
                    Paragraph para = (Paragraph)srcNode;
                    if (para.IsEndOfSection && !para.HasChildNodes)
                        continue;
                }

                // This creates a clone of the node, suitable for insertion into the destination document
                Node newNode = importer.ImportNode(srcNode, true);

                // Insert new node after the reference node
                dstStory.InsertAfter(newNode, insertionDestination);
                insertionDestination = newNode;
            }
    }
    else
    {
        throw new ArgumentException("The destination node should be either a paragraph or table.");
    }
}

See Also