com.aspose.words

  • java.lang.Object
    • com.aspose.words.Range
public class Range 
extends java.lang.Object

Represents a contiguous area in a document.

The document is represented by a tree of nodes and the nodes provide operations to work with the tree, but some operations are easier to perform if the document is treated as a contiguous sequence of text.

Range is a "facade" interface that provide methods that treat the document or portions of the document as "flat" text regardless of the fact that the document nodes are stored in a tree-like object model.

Range does not contain any text or nodes, it is merely a view or "window" over a fragment of a document.

Example:

Shows how to get the text contents of all the nodes that a range covers.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.write("Hello world!");

Assert.assertEquals("Hello world!", doc.getRange().getText().trim());

Property Getters/Setters Summary
BookmarkCollectiongetBookmarks()
Returns a Bookmarks collection that represents all bookmarks in the range.
FieldCollectiongetFields()
Returns a Fields collection that represents all fields in the range.
FormFieldCollectiongetFormFields()
Returns a FormFields collection that represents all form fields in the range.
java.lang.StringgetText()
Gets the text of the range.
 
Method Summary
voiddelete()
Deletes all characters of the range.
voidnormalizeFieldTypes()
Changes field type values FieldChar.FieldType of FieldStart, FieldSeparator, FieldEnd in this range so that they correspond to the field types contained in the field codes.
intreplace(java.lang.String pattern, java.lang.String replacement)
Replaces all occurrences of a specified character string pattern with a replacement string.
intreplace(java.lang.String pattern, java.lang.String replacement, FindReplaceOptions options)
Replaces all occurrences of a specified character string pattern with a replacement string.
intreplace(java.util.regex.Pattern pattern, java.lang.String replacement)
Replaces all occurrences of a character pattern specified by a regular expression with another string.
intreplace(java.util.regex.Pattern pattern, java.lang.String replacement, FindReplaceOptions options)
Replaces all occurrences of a character pattern specified by a regular expression with another string.
DocumenttoDocument()
Constructs a new fully formed document that contains the range.
voidunlinkFields()
Unlinks fields in this range.
voidupdateFields()
Updates the values of document fields in this range.
 

    • Property Getters/Setters Detail

      • getBookmarks

        public BookmarkCollection getBookmarks()
        
        Returns a Bookmarks collection that represents all bookmarks in the range.

        Example:

        Shows how to add bookmarks and update their contents.
        public void createUpdateAndPrintBookmarks() throws Exception {
            // Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
            Document doc = createDocumentWithBookmarks(3);
            BookmarkCollection bookmarks = doc.getRange().getBookmarks();
        
            printAllBookmarkInfo(bookmarks);
        
            // Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
            bookmarks.get(0).setName("{bookmarks[0].Name}_NewName");
            bookmarks.get("MyBookmark_2").setText("Updated text contents of {bookmarks[1].Name}");
        
            // Print all bookmarks again to see updated values.
            printAllBookmarkInfo(bookmarks);
        }
        
        /// <summary>
        /// Create a document with a given number of bookmarks.
        /// </summary>
        private static Document createDocumentWithBookmarks(int numberOfBookmarks) throws Exception {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            for (int i = 1; i <= numberOfBookmarks; i++) {
                String bookmarkName = "MyBookmark_" + i;
        
                builder.write("Text before bookmark.");
                builder.startBookmark(bookmarkName);
                builder.write(MessageFormat.format("Text inside {0}.", bookmarkName));
                builder.endBookmark(bookmarkName);
                builder.writeln("Text after bookmark.");
            }
        
            return doc;
        }
        
        /// <summary>
        /// Use an iterator and a visitor to print info of every bookmark in the collection.
        /// </summary>
        private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception {
            BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
        
            // Get each bookmark in the collection to accept a visitor that will print its contents.
            Iterator<Bookmark> enumerator = bookmarks.iterator();
        
            while (enumerator.hasNext()) {
                Bookmark currentBookmark = enumerator.next();
        
                if (currentBookmark != null) {
                    currentBookmark.getBookmarkStart().accept(bookmarkVisitor);
                    currentBookmark.getBookmarkEnd().accept(bookmarkVisitor);
        
                    System.out.println(currentBookmark.getBookmarkStart().getText());
                }
            }
        }
        
        /// <summary>
        /// Prints contents of every visited bookmark to the console.
        /// </summary>
        public static class BookmarkInfoPrinter extends DocumentVisitor {
            public int visitBookmarkStart(BookmarkStart bookmarkStart) throws Exception {
                System.out.println(MessageFormat.format("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.getName(),
                        bookmarkStart.getBookmark().getText()));
                return VisitorAction.CONTINUE;
            }
        
            public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) {
                System.out.println(MessageFormat.format("BookmarkEnd name: \"{0}\"", bookmarkEnd.getName()));
                return VisitorAction.CONTINUE;
            }
        }
      • getFields

        public FieldCollection getFields()
        
        Returns a Fields collection that represents all fields in the range.
      • getFormFields

        public FormFieldCollection getFormFields()
        
        Returns a FormFields collection that represents all form fields in the range.

        Example:

        Shows how insert different kinds of form fields into a document, and process them with using a document visitor implementation.
        public void visitor() throws Exception {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            // Use a document builder to insert a combo box.
            builder.write("Choose a value from this combo box: ");
            FormField comboBox = builder.insertComboBox("MyComboBox", new String[]{"One", "Two", "Three"}, 0);
            comboBox.setCalculateOnExit(true);
            Assert.assertEquals(3, comboBox.getDropDownItems().getCount());
            Assert.assertEquals(0, comboBox.getDropDownSelectedIndex());
            Assert.assertTrue(comboBox.getEnabled());
        
            builder.insertBreak(BreakType.PARAGRAPH_BREAK);
        
            // Use a document builder to insert a check box.
            builder.write("Click this check box to tick/untick it: ");
            FormField checkBox = builder.insertCheckBox("MyCheckBox", false, 50);
            checkBox.isCheckBoxExactSize(true);
            checkBox.setHelpText("Right click to check this box");
            checkBox.setOwnHelp(true);
            checkBox.setStatusText("Checkbox status text");
            checkBox.setOwnStatus(true);
            Assert.assertEquals(50.0d, checkBox.getCheckBoxSize());
            Assert.assertFalse(checkBox.getChecked());
            Assert.assertFalse(checkBox.getDefault());
        
            builder.insertBreak(BreakType.PARAGRAPH_BREAK);
        
            // Use a document builder to insert text input form field.
            builder.write("Enter text here: ");
            FormField textInput = builder.insertTextInput("MyTextInput", TextFormFieldType.REGULAR, "", "Placeholder text", 50);
            textInput.setEntryMacro("EntryMacro");
            textInput.setExitMacro("ExitMacro");
            textInput.setTextInputDefault("Regular");
            textInput.setTextInputFormat("FIRST CAPITAL");
            textInput.setTextInputValue("New placeholder text");
            Assert.assertEquals(TextFormFieldType.REGULAR, textInput.getTextInputType());
            Assert.assertEquals(50, textInput.getMaxLength());
        
            // This collection contains all our form fields.
            FormFieldCollection formFields = doc.getRange().getFormFields();
            Assert.assertEquals(3, formFields.getCount());
        
            // Fields display our form fields. We can see their field codes by opening this document
            // in Microsoft and pressing Alt + F9. These fields have no switches,
            // and members of the FormField object fully govern their form fields' content.
            Assert.assertEquals(3, doc.getRange().getFields().getCount());
            Assert.assertEquals(" FORMDROPDOWN \u0001", doc.getRange().getFields().get(0).getFieldCode());
            Assert.assertEquals(" FORMCHECKBOX \u0001", doc.getRange().getFields().get(1).getFieldCode());
            Assert.assertEquals(" FORMTEXT \u0001", doc.getRange().getFields().get(2).getFieldCode());
        
            // Allow each form field to accept a document visitor.
            FormFieldVisitor formFieldVisitor = new FormFieldVisitor();
        
            Iterator<FormField> fieldEnumerator = formFields.iterator();
            while (fieldEnumerator.hasNext())
                fieldEnumerator.next().accept(formFieldVisitor);
        
            System.out.println(formFieldVisitor.getText());
        
            doc.updateFields();
            doc.save(getArtifactsDir() + "FormFields.Visitor.html");
        }
        
        /// <summary>
        /// Visitor implementation that prints details of form fields that it visits. 
        /// </summary>
        public static class FormFieldVisitor extends DocumentVisitor {
            public FormFieldVisitor() {
                mBuilder = new StringBuilder();
            }
        
            /// <summary>
            /// Called when a FormField node is encountered in the document.
            /// </summary>
            public /*override*/ /*VisitorAction*/int visitFormField(FormField formField) {
                appendLine(formField.getType() + ": \"" + formField.getName() + "\"");
                appendLine("\tStatus: " + (formField.getEnabled() ? "Enabled" : "Disabled"));
                appendLine("\tHelp Text:  " + formField.getHelpText());
                appendLine("\tEntry macro name: " + formField.getEntryMacro());
                appendLine("\tExit macro name: " + formField.getExitMacro());
        
                switch (formField.getType()) {
                    case FieldType.FIELD_FORM_DROP_DOWN:
                        appendLine("\tDrop down items count: " + formField.getDropDownItems().getCount() + ", default selected item index: " + formField.getDropDownSelectedIndex());
                        appendLine("\tDrop down items: " + String.join(", ", formField.getDropDownItems()));
                        break;
                    case FieldType.FIELD_FORM_CHECK_BOX:
                        appendLine("\tCheckbox size: " + formField.getCheckBoxSize());
                        appendLine("\t" + "Checkbox is currently: " + (formField.getChecked() ? "checked, " : "unchecked, ") + "by default: " + (formField.getDefault() ? "checked" : "unchecked"));
                        break;
                    case FieldType.FIELD_FORM_TEXT_INPUT:
                        appendLine("\tInput format: " + formField.getTextInputFormat());
                        appendLine("\tCurrent contents: " + formField.getResult());
                        break;
                }
        
                // Let the visitor continue visiting other nodes.
                return VisitorAction.CONTINUE;
            }
        
            /// <summary>
            /// Adds newline char-terminated text to the current output.
            /// </summary>
            private void appendLine(String text) {
                mBuilder.append(text + '\n');
            }
        
            /// <summary>
            /// Gets the plain text of the document that was accumulated by the visitor.
            /// </summary>
            public String getText() {
                return mBuilder.toString();
            }
        
            private final StringBuilder mBuilder;
        }
      • getText

        public java.lang.String getText()
        
        Gets the text of the range.

        The returned string includes all control and special characters as described in ControlChar.

        Example:

        Shows how to get the text contents of all the nodes that a range covers.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.write("Hello world!");
        
        Assert.assertEquals("Hello world!", doc.getRange().getText().trim());
    • Method Detail

      • delete

        public void delete()
        Deletes all characters of the range.

        Example:

        Shows how to delete all the nodes from a range.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Add text to the first section in the document, and then add another section.
        builder.write("Section 1. ");
        builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
        builder.write("Section 2.");
        
        Assert.assertEquals("Section 1. \fSection 2.", doc.getText().trim());
        
        // Remove the first section entirely by removing all the nodes
        // within its range, including the section itself.
        doc.getSections().get(0).getRange().delete();
        
        Assert.assertEquals(1, doc.getSections().getCount());
        Assert.assertEquals("Section 2.", doc.getText().trim());
      • replace

        public int replace(java.lang.String pattern, java.lang.String replacement)
                   throws java.lang.Exception
        Replaces all occurrences of a specified character string pattern with a replacement string.

        The pattern will not be used as regular expression. Please use replace(java.util.regex.Pattern,java.lang.String) if you need regular expressions.

        Used case-insensitive comparison.

        Method is able to process breaks in both pattern and replacement strings.

        You should use special meta-characters if you need to work with breaks:
        • &p - paragraph break
        • &b - section break
        • &m - page break
        • &l - manual line break
        Use method replace(java.lang.String,java.lang.String,com.aspose.words.FindReplaceOptions) to have more flexible customization.
        Parameters:
        pattern - A string to be replaced.
        replacement - A string to replace all occurrences of pattern.
        Returns:
        The number of replacements made.

        Example:

        Shows how to add formatting to paragraphs in which a find-and-replace operation has found matches.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.writeln("Every paragraph that ends with a full stop like this one will be right aligned.");
        builder.writeln("This one will not!");
        builder.write("This one also will.");
        
        ParagraphCollection paragraphs = doc.getFirstSection().getBody().getParagraphs();
        
        Assert.assertEquals(ParagraphAlignment.LEFT, paragraphs.get(0).getParagraphFormat().getAlignment());
        Assert.assertEquals(ParagraphAlignment.LEFT, paragraphs.get(1).getParagraphFormat().getAlignment());
        Assert.assertEquals(ParagraphAlignment.LEFT, paragraphs.get(2).getParagraphFormat().getAlignment());
        
        // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
        FindReplaceOptions options = new FindReplaceOptions();
        
        // Set the "Alignment" property to "ParagraphAlignment.Right" to right-align every paragraph
        // that contains a match that the find-and-replace operation finds.
        options.getApplyParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);
        
        // Replace every full stop that is right before a paragraph break with an exclamation point.
        int count = doc.getRange().replace(".&p", "!&p", options);
        
        Assert.assertEquals(2, count);
        Assert.assertEquals(ParagraphAlignment.RIGHT, paragraphs.get(0).getParagraphFormat().getAlignment());
        Assert.assertEquals(ParagraphAlignment.LEFT, paragraphs.get(1).getParagraphFormat().getAlignment());
        Assert.assertEquals(ParagraphAlignment.RIGHT, paragraphs.get(2).getParagraphFormat().getAlignment());
        Assert.assertEquals("Every paragraph that ends with a full stop like this one will be right aligned!\r" +
                "This one will not!\r" +
                "This one also will!", doc.getText().trim());

        Example:

        Shows how to perform a find-and-replace text operation on the contents of a document.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.writeln("Greetings, _FullName_!");
        
        // Perform a find-and-replace operation on our document's contents and verify the number of replacements that took place.
        int replacementCount = doc.getRange().replace("_FullName_", "John Doe");
        
        Assert.assertEquals(1, replacementCount);
        Assert.assertEquals("Greetings, John Doe!", doc.getText().trim());

        Example:

                     Document doc = new Document();
                     DocumentBuilder builder = new DocumentBuilder(doc);
                     builder.Writeln("Numbers 1, 2, 3");
                    
                     // Inserts paragraph break after Numbers.
                     doc.Range.Replace("Numbers", "Numbers&p", new FindReplaceOptions());
                     
      • replace

        public int replace(java.lang.String pattern, java.lang.String replacement, FindReplaceOptions options)
                   throws java.lang.Exception
        Replaces all occurrences of a specified character string pattern with a replacement string.

        The pattern will not be used as regular expression. Please use replace(java.util.regex.Pattern,java.lang.String,com.aspose.words.FindReplaceOptions) if you need regular expressions.

        Method is able to process breaks in both pattern and replacement strings.

        You should use special meta-characters if you need to work with breaks:
        • &p - paragraph break
        • &b - section break
        • &m - page break
        • &l - manual line break
        • && - & character
        Parameters:
        pattern - A string to be replaced.
        replacement - A string to replace all occurrences of pattern.
        options - FindReplaceOptions object to specify additional options.
        Returns:
        The number of replacements made.

        Example:

        Shows how to replace all instances of String of text in a table and cell.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        Table table = builder.startTable();
        builder.insertCell();
        builder.write("Carrots");
        builder.insertCell();
        builder.write("50");
        builder.endRow();
        builder.insertCell();
        builder.write("Potatoes");
        builder.insertCell();
        builder.write("50");
        builder.endTable();
        
        FindReplaceOptions options = new FindReplaceOptions();
        options.setMatchCase(true);
        options.setFindWholeWordsOnly(true);
        
        // Perform a find-and-replace operation on an entire table.
        table.getRange().replace("Carrots", "Eggs", options);
        
        // Perform a find-and-replace operation on the last cell of the last row of the table.
        table.getLastRow().getLastCell().getRange().replace("50", "20", options);
        
        Assert.assertEquals("Eggs\u000750\u0007\u0007" +
                        "Potatoes\u000720", table.getText().trim());

        Example:

        Shows how to toggle standalone word-only find-and-replace operations.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.writeln("Jackson will meet you in Jacksonville.");
        
        // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
        FindReplaceOptions options = new FindReplaceOptions();
        
        // Set the "FindWholeWordsOnly" flag to "true" to replace the found text if it is not a part of another word.
        // Set the "FindWholeWordsOnly" flag to "false" to replace all text regardless of its surroundings.
        options.setFindWholeWordsOnly(findWholeWordsOnly);
        
        doc.getRange().replace("Jackson", "Louis", options);
        
        Assert.assertEquals(
                findWholeWordsOnly ? "Louis will meet you in Jacksonville." : "Louis will meet you in Louisville.",
                doc.getText().trim());

        Example:

        Shows how to toggle case sensitivity when performing a find-and-replace operation.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.writeln("Ruby bought a ruby necklace.");
        
        // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
        FindReplaceOptions options = new FindReplaceOptions();
        
        // Set the "MatchCase" flag to "true" to apply case sensitivity while finding strings to replace.
        // Set the "MatchCase" flag to "false" to ignore character case while searching for text to replace.
        options.setMatchCase(matchCase);
        
        doc.getRange().replace("Ruby", "Jade", options);
        
        Assert.assertEquals(matchCase ? "Jade bought a ruby necklace." : "Jade bought a Jade necklace.",
                doc.getText().trim());

        Example:

        Shows how to replace text in a document's footer.
        Document doc = new Document(getMyDir() + "Footer.docx");
        
        HeaderFooterCollection headersFooters = doc.getFirstSection().getHeadersFooters();
        HeaderFooter footer = headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
        
        FindReplaceOptions options = new FindReplaceOptions();
        options.setMatchCase(false);
        options.setFindWholeWordsOnly(false);
        
        int currentYear = Calendar.YEAR;
        footer.getRange().replace("(C) 2006 Aspose Pty Ltd.", MessageFormat.format("Copyright (C) {0} by Aspose Pty Ltd.", currentYear), options);
        
        doc.save(getArtifactsDir() + "HeaderFooter.ReplaceText.docx");

        Example:

                     Document doc = new Document();
                     DocumentBuilder builder = new DocumentBuilder(doc);
                     builder.Writeln("Numbers 1, 2, 3");
                    
                     // Inserts paragraph break after Numbers.
                     doc.Range.Replace("Numbers", "Numbers&p", new FindReplaceOptions());
                     
      • replace

        public int replace(java.util.regex.Pattern pattern, java.lang.String replacement)
                   throws java.lang.Exception
        Replaces all occurrences of a character pattern specified by a regular expression with another string.

        Replaces the whole match captured by the regular expression.

        Method is able to process breaks in both pattern and replacement strings.

        You should use special meta-characters if you need to work with breaks:
        • &p - paragraph break
        • &b - section break
        • &m - page break
        • &l - manual line break
        Use method replace(java.util.regex.Pattern,java.lang.String,com.aspose.words.FindReplaceOptions) to have more flexible customization.
        Parameters:
        pattern - A regular expression pattern used to find matches.
        replacement - A string to replace all occurrences of pattern.
        Returns:
        The number of replacements made.

        Example:

        Shows how to replace all occurrences of a regular expression pattern with other text.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.writeln("I decided to get the curtains in gray, ideal for the grey-accented room.");
        
        doc.getRange().replace(Pattern.compile("gr(a|e)y"), "lavender");
        
        Assert.assertEquals("I decided to get the curtains in lavender, ideal for the lavender-accented room.", doc.getText().trim());

        Example:

                     Document doc = new Document();
                     DocumentBuilder builder = new DocumentBuilder(doc);
                     builder.Writeln("a1, b2, c3");
                    
                     // Replaces each number with paragraph break.
                     doc.Range.Replace(new Regex(@"\d+"), "&p");
                     
      • replace

        public int replace(java.util.regex.Pattern pattern, java.lang.String replacement, FindReplaceOptions options)
                   throws java.lang.Exception
        Replaces all occurrences of a character pattern specified by a regular expression with another string.

        Replaces the whole match captured by the regular expression.

        Method is able to process breaks in both pattern and replacement strings.

        You should use special meta-characters if you need to work with breaks:
        • &p - paragraph break
        • &b - section break
        • &m - page break
        • &l - manual line break
        • && - & character
        Parameters:
        pattern - A regular expression pattern used to find matches.
        replacement - A string to replace all occurrences of pattern.
        options - FindReplaceOptions object to specify additional options.
        Returns:
        The number of replacements made.

        Example:

        Shows how to insert an entire document's contents as a replacement of a match in a find-and-replace operation.
        public void insertDocumentAtReplace() throws Exception {
            Document mainDoc = new Document(getMyDir() + "Document insertion destination.docx");
        
            // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
            FindReplaceOptions options = new FindReplaceOptions();
            options.setReplacingCallback(new InsertDocumentAtReplaceHandler());
        
            mainDoc.getRange().replace(Pattern.compile("\\[MY_DOCUMENT\\]"), "", options);
            mainDoc.save(getArtifactsDir() + "InsertDocument.InsertDocumentAtReplace.docx");
        
        }
        
        private static class InsertDocumentAtReplaceHandler implements IReplacingCallback {
            public int replacing(ReplacingArgs args) throws Exception {
                Document subDoc = new Document(getMyDir() + "Document.docx");
        
                // Insert a document after the paragraph containing the matched text.
                Paragraph para = (Paragraph) args.getMatchNode().getParentNode();
                insertDocument(para, subDoc);
        
                // Remove the paragraph with the matched text.
                para.remove();
        
                return ReplaceAction.SKIP;
            }
        }
        
        /// <summary>
        /// Inserts all the nodes of another document after a paragraph or table.
        /// </summary>
        private static void insertDocument(Node insertionDestination, Document docToInsert) {
            if (((insertionDestination.getNodeType()) == (NodeType.PARAGRAPH)) || ((insertionDestination.getNodeType()) == (NodeType.TABLE))) {
                CompositeNode dstStory = insertionDestination.getParentNode();
        
                NodeImporter importer =
                        new NodeImporter(docToInsert, insertionDestination.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);
        
                for (Section srcSection : docToInsert.getSections())
                    for (Node srcNode : srcSection.getBody()) {
                        // Skip the node if it is the last empty paragraph in a section.
                        if (((srcNode.getNodeType()) == (NodeType.PARAGRAPH))) {
                            Paragraph para = (Paragraph) srcNode;
                            if (para.isEndOfSection() && !para.hasChildNodes())
                                continue;
                        }
        
                        Node newNode = importer.importNode(srcNode, true);
        
                        dstStory.insertAfter(newNode, insertionDestination);
                        insertionDestination = newNode;
                    }
            } else {
                throw new IllegalArgumentException("The destination node must be either a paragraph or table.");
            }
        }

        Example:

        Shows how to replace all occurrences of a regular expression pattern with another string, while tracking all such replacements.
        public void replaceWithCallback() throws Exception {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            builder.writeln("Our new location in New York City is opening tomorrow. " +
                    "Hope to see all our NYC-based customers at the opening!");
        
            // We can use a "FindReplaceOptions" object to modify the find-and-replace process.
            FindReplaceOptions options = new FindReplaceOptions();
        
            // Set a callback that tracks any replacements that the "Replace" method will make.
            TextFindAndReplacementLogger logger = new TextFindAndReplacementLogger();
            options.setReplacingCallback(logger);
        
            doc.getRange().replace(Pattern.compile("New York City|NYC"), "Washington", options);
        
            Assert.assertEquals("Our new location in (Old value:\"New York City\") Washington is opening tomorrow. " +
                    "Hope to see all our (Old value:\"NYC\") Washington-based customers at the opening!", doc.getText().trim());
        
            Assert.assertEquals("\"New York City\" converted to \"Washington\" 20 characters into a 21 node." +
                    "\"NYC\" converted to \"Washington\" 42 characters into a 21 node.", logger.getLog().trim());
        }
        
        /// <summary>
        /// Maintains a log of every text replacement done by a find-and-replace operation
        /// and notes the original matched text's value.
        /// </summary>
        private static class TextFindAndReplacementLogger implements IReplacingCallback {
            public int replacing(ReplacingArgs args) {
                mLog.append(MessageFormat.format("\"{0}\" converted to \"{1}\" {2} characters into a {3} node.", args.getMatch().group(0), args.getReplacement(), args.getMatchOffset(), args.getMatchNode().getNodeType()));
        
                args.setReplacement(MessageFormat.format("(Old value:\"{0}\") {1}", args.getMatch().group(0), args.getReplacement()));
                return ReplaceAction.REPLACE;
            }
        
            public String getLog() {
                return mLog.toString();
            }
        
            private final StringBuilder mLog = new StringBuilder();
        }

        Example:

                     Document doc = new Document();
                     DocumentBuilder builder = new DocumentBuilder(doc);
                     builder.Writeln("a1, b2, c3");
                    
                     // Replaces each number with paragraph break.
                     doc.Range.Replace(new Regex(@"\d+"), "&p", new FindReplaceOptions());
                     
      • toDocument

        public Document toDocument()
                           throws java.lang.Exception
        Constructs a new fully formed document that contains the range.
      • unlinkFields

        public void unlinkFields()
                         throws java.lang.Exception
        Unlinks fields in this range.

        Replaces all the fields in this range with their most recent results.

        To unlink fields in the whole document use unlinkFields().

        Example:

        Shows how to unlink all fields in a range.
        Document doc = new Document(getMyDir() + "Linked fields.docx");
        
        Section newSection = (Section) doc.getSections().get(0).deepClone(true);
        doc.getSections().add(newSection);
        
        doc.getSections().get(1).getRange().unlinkFields();
      • updateFields

        public void updateFields()
                         throws java.lang.Exception
        Updates the values of document fields in this range.

        When you open, modify and then save a document, Aspose.Words does not update fields automatically, it keeps them intact. Therefore, you would usually want to call this method before saving if you have modified the document programmatically and want to make sure the proper (calculated) field values appear in the saved document.

        There is no need to update fields after executing a mail merge because mail merge is a kind of field update and automatically updates all fields in the document.

        This method does not update all field types. For the detailed list of supported field types, see the Programmers Guide.

        This method does not update fields that are related to the page layout algorithms (e.g. PAGE, PAGES, PAGEREF). The page layout-related fields are updated when you render a document or call Document.updatePageLayout().

        To update fields in the whole document use Document.updateFields().

        Example:

        Shows how to update all the fields in a range.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.insertField(" DOCPROPERTY Category");
        builder.insertBreak(BreakType.SECTION_BREAK_EVEN_PAGE);
        builder.insertField(" DOCPROPERTY Category");
        
        // The above DOCPROPERTY fields will display the value of this built-in document property.
        doc.getBuiltInDocumentProperties().setCategory("MyCategory");
        
        // If we update the value of a document property, we will need to update all the DOCPROPERTY fields to display it.
        Assert.assertEquals("", doc.getRange().getFields().get(0).getResult());
        Assert.assertEquals("", doc.getRange().getFields().get(1).getResult());
        
        // Update all the fields that are in the range of the first section.
        doc.getFirstSection().getRange().updateFields();
        
        Assert.assertEquals("MyCategory", doc.getRange().getFields().get(0).getResult());
        Assert.assertEquals("", doc.getRange().getFields().get(1).getResult());