com.aspose.words

Interface IReplacingCallback

  • public interface IReplacingCallback 

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

Example:

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

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

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

    doc.getRange().replace(Pattern.compile(" <CustomerName>,"), "", options);

    // Save the modified document
    doc.save(getArtifactsDir() + "Range.ReplaceWithInsertHtml.docx");
}

private class ReplaceWithHtmlEvaluator implements IReplacingCallback {
    ReplaceWithHtmlEvaluator(final FindReplaceOptions options) {
        mOptions = options;
    }

    /**
     * NOTE: This is a simplistic method that will only work well when the match
     * starts at the beginning of a run.
     */
    public int replacing(final ReplacingArgs e) throws Exception {
        DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
        builder.moveTo(e.getMatchNode());

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

        return ReplaceAction.REPLACE;
    }

    private FindReplaceOptions mOptions;
}

Example:

Show changes for headers and footers order.
public void headerFooterOrder() throws Exception {
    Document doc = new Document(getMyDir() + "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.getFirstSection();
    Assert.assertEquals(firstPageSection.getPageSetup().getDifferentFirstPageHeaderFooter(), true);

    FindReplaceOptions options = new FindReplaceOptions();
    ReplaceLog logger = new ReplaceLog();
    options.setReplacingCallback(logger);

    doc.getRange().replace(Pattern.compile("(header|footer)"), "", options);

    doc.save(getArtifactsDir() + "HeaderFooter.HeaderFooterOrder.docx");

    Assert.assertEquals(logger.getText(), "First header\r\nFirst footer\r\nSecond header\r\nSecond footer\r\nThird header\r\n" + "Third footer\r\n");

    // 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.getPageSetup().setDifferentFirstPageHeaderFooter(false);

    doc.getRange().replace(Pattern.compile("(header|footer)"), "", options);
    Assert.assertEquals(logger.getText(), "Third header\r\nFirst header\r\nThird footer\r\nFirst footer\r\nSecond header\r\nSecond footer\r\n");
}

private static class ReplaceLog implements IReplacingCallback {
    public int replacing(final ReplacingArgs args) {
        mTextBuilder.append(args.getMatchNode().getText() + "\r\n");
        return ReplaceAction.SKIP;
    }

    void clearText() {
        mTextBuilder.setLength(0);
    }

    String getText() {
        return mTextBuilder.toString();
    }

    private StringBuilder mTextBuilder = new StringBuilder();
}

Example:

Shows how to insert content of one document into another during a customized find and replace operation.
public void insertDocumentAtReplace() throws Exception {
    Document mainDoc = new Document(getMyDir() + "Document insertion destination.docx");

    FindReplaceOptions options = new FindReplaceOptions();
    options.setDirection(FindReplaceDirection.BACKWARD);
    options.setReplacingCallback(new InsertDocumentAtReplaceHandler());

    mainDoc.getRange().replace("[MY_DOCUMENT]", "", options);
    mainDoc.save(getArtifactsDir() + "InsertDocument.InsertDocumentAtReplace.docx");
}

private static class InsertDocumentAtReplaceHandler implements IReplacingCallback {
    public /*ReplaceAction*/int /*IReplacingCallback.*/replacing(ReplacingArgs args) throws Exception {
        Document subDoc = new Document(getMyDir() + "Document.docx");

        // Insert a document after the paragraph, containing the match text
        Paragraph para = (Paragraph) args.getMatchNode().getParentNode();
        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.getNodeType()) == (NodeType.PARAGRAPH)) || ((insertionDestination.getNodeType()) == (NodeType.TABLE))) {
        // We will be inserting into the parent of the destination paragraph
        CompositeNode dstStory = insertionDestination.getParentNode();

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

        // Loop through all block level nodes in the body of the section
        for (Section srcSection : docToInsert.getSections())
            for (Node srcNode : srcSection.getBody()) {
                // Let's skip the node if it is a last empty paragraph in a section
                if (((srcNode.getNodeType()) == (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 IllegalArgumentException("The destination node should be either a paragraph or table.");
    }
}

Method Summary
abstract intreplacing(ReplacingArgs args)
A user defined method that is called during a replace operation for each match found just before a replace is made.
 

    • Method Detail

      • replacing

        public abstract int replacing(ReplacingArgs args)
                                   throws java.lang.Exception
        A user defined method that is called during a replace operation for each match found just before a replace is made.
        Returns:
        A ReplaceAction value. A ReplaceAction value that specifies the action to be taken for the current match.

        Example:

        Shows how to insert content of one document into another during a customized find and replace operation.
        public void insertDocumentAtReplace() throws Exception {
            Document mainDoc = new Document(getMyDir() + "Document insertion destination.docx");
        
            FindReplaceOptions options = new FindReplaceOptions();
            options.setDirection(FindReplaceDirection.BACKWARD);
            options.setReplacingCallback(new InsertDocumentAtReplaceHandler());
        
            mainDoc.getRange().replace("[MY_DOCUMENT]", "", options);
            mainDoc.save(getArtifactsDir() + "InsertDocument.InsertDocumentAtReplace.docx");
        }
        
        private static class InsertDocumentAtReplaceHandler implements IReplacingCallback {
            public /*ReplaceAction*/int /*IReplacingCallback.*/replacing(ReplacingArgs args) throws Exception {
                Document subDoc = new Document(getMyDir() + "Document.docx");
        
                // Insert a document after the paragraph, containing the match text
                Paragraph para = (Paragraph) args.getMatchNode().getParentNode();
                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.getNodeType()) == (NodeType.PARAGRAPH)) || ((insertionDestination.getNodeType()) == (NodeType.TABLE))) {
                // We will be inserting into the parent of the destination paragraph
                CompositeNode dstStory = insertionDestination.getParentNode();
        
                // This object will be translating styles and lists during the import
                NodeImporter importer =
                        new NodeImporter(docToInsert, insertionDestination.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);
        
                // Loop through all block level nodes in the body of the section
                for (Section srcSection : docToInsert.getSections())
                    for (Node srcNode : srcSection.getBody()) {
                        // Let's skip the node if it is a last empty paragraph in a section
                        if (((srcNode.getNodeType()) == (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 IllegalArgumentException("The destination node should be either a paragraph or table.");
            }
        }

        Example:

        Replaces text specified with regular expression with HTML.
        public void replaceWithInsertHtml() throws Exception {
            // Open the document
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.writeln("Hello <CustomerName>,");
        
            FindReplaceOptions options = new FindReplaceOptions();
            options.setReplacingCallback(new ReplaceWithHtmlEvaluator(options));
        
            doc.getRange().replace(Pattern.compile(" <CustomerName>,"), "", options);
        
            // Save the modified document
            doc.save(getArtifactsDir() + "Range.ReplaceWithInsertHtml.docx");
        }
        
        private class ReplaceWithHtmlEvaluator implements IReplacingCallback {
            ReplaceWithHtmlEvaluator(final FindReplaceOptions options) {
                mOptions = options;
            }
        
            /**
             * NOTE: This is a simplistic method that will only work well when the match
             * starts at the beginning of a run.
             */
            public int replacing(final ReplacingArgs e) throws Exception {
                DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
                builder.moveTo(e.getMatchNode());
        
                // Replace '<CustomerName>' text with a red bold name
                builder.insertHtml("<b><font color='red'>James Bond, </font></b>");
                e.setReplacement("");
        
                return ReplaceAction.REPLACE;
            }
        
            private FindReplaceOptions mOptions;
        }