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 plain, unformatted text of a range.
Document doc = new Document(getMyDir() + "Document.docx");
String text = doc.getRange().getText();

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 character pattern specified by a regular expression with another string.
intreplace(java.lang.String pattern, java.lang.String replacement, FindReplaceOptions options)
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)
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 3 bookmarks: "MyBookmark 1", "MyBookmark 2", "MyBookmark 3"
            Document doc = createDocumentWithBookmarks();
            BookmarkCollection bookmarks = doc.getRange().getBookmarks();
        
            // Check that we have 3 bookmarks
            Assert.assertEquals(bookmarks.getCount(), 3);
        
            // Look at initial values of our bookmarks
            printAllBookmarkInfo(bookmarks);
        
            // Obtain bookmarks from a bookmark collection by index/name and update their values
            bookmarks.get(0).setName("Updated name of " + bookmarks.get(0).getName());
            bookmarks.get("MyBookmark 2").setText("Updated text content of " + bookmarks.get(1).getName());
            // Remove the latest bookmark
            // The bookmarked text is not deleted
            bookmarks.get(2).remove();
        
            bookmarks = doc.getRange().getBookmarks();
            // Check that we have 2 bookmarks after the latest bookmark was deleted
            Assert.assertEquals(bookmarks.getCount(), 2);
        
            // Look at updated values of our bookmarks
            printAllBookmarkInfo(bookmarks);
        }
        
        /// <summary>
        /// Create a document with bookmarks using the start and end nodes.
        /// </summary>
        private static Document createDocumentWithBookmarks() throws Exception {
            DocumentBuilder builder = new DocumentBuilder();
            Document doc = builder.getDocument();
        
            // An empty document has just one empty paragraph by default
            Paragraph p = doc.getFirstSection().getBody().getFirstParagraph();
        
            // Add several bookmarks to the document
            for (int i = 1; i <= 3; i++) {
                String bookmarkName = "MyBookmark " + i;
        
                p.appendChild(new Run(doc, "Text before bookmark."));
        
                p.appendChild(new BookmarkStart(doc, bookmarkName));
                p.appendChild(new Run(doc, "Text content of " + bookmarkName));
                p.appendChild(new BookmarkEnd(doc, bookmarkName));
        
                p.appendChild(new Run(doc, "Text after bookmark.\r\n"));
            }
        
            return builder.getDocument();
        }
        
        /// <summary>
        /// Use an iterator and a visitor to print info of every bookmark from within a document.
        /// </summary>
        private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception {
            // Create a DocumentVisitor
            BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
        
            // Get the enumerator from the document's BookmarkCollection and iterate over the bookmarks
            Iterator<Bookmark> enumerator = bookmarks.iterator();
        
            while (enumerator.hasNext()) {
                Bookmark currentBookmark = enumerator.next();
        
                // Accept our DocumentVisitor it to print information about our bookmarks
                if (currentBookmark != null) {
                    currentBookmark.getBookmarkStart().accept(bookmarkVisitor);
                    currentBookmark.getBookmarkEnd().accept(bookmarkVisitor);
        
                    // Prints a blank line
                    System.out.println(currentBookmark.getBookmarkStart().getText());
                }
            }
        }
        
        /// <summary>
        /// Visitor that prints bookmark information 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 to get a collection of form fields.
        Document doc = new Document(getMyDir() + "Form fields.docx");
        FormFieldCollection formFields = doc.getRange().getFormFields();
      • 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 plain, unformatted text of a range.
        Document doc = new Document(getMyDir() + "Document.docx");
        String text = doc.getRange().getText();
    • Method Detail

      • delete

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

        Example:

        Shows how to delete all characters of a range.
        // Insert two sections into a blank document
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.write("Section 1. ");
        builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
        builder.write("Section 2.");
        
        // Verify the whole text of the document
        Assert.assertEquals("Section 1. \fSection 2.", doc.getText().trim());
        
        // Delete the first section from the document
        doc.getSections().get(0).getRange().delete();
        
        // Check the first section was deleted by looking at the text of the whole document again
        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 character pattern specified by a regular expression with another string.

        Used case-insensitive comparison.

        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.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:

                     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 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
        To leave any meta-character intact a parameter FindReplaceOptions.PreserveMetaCharacters should be set to true.
        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);
        
        // Create a table and give it conditional styling on border colors based on the row being the first or last
        Table table = builder.startTable();
        builder.insertCell();
        builder.write("Carrots");
        builder.insertCell();
        builder.write("30");
        builder.endRow();
        builder.insertCell();
        builder.write("Potatoes");
        builder.insertCell();
        builder.write("50");
        builder.endTable();
        
        FindReplaceOptions options = new FindReplaceOptions();
        options.setMatchCase(true);
        options.setFindWholeWordsOnly(true);
        
        // Replace any instances of our String in the entire table
        table.getRange().replace("Carrots", "Eggs", options);
        // Replace any instances of our String in the last cell of the table only
        table.getLastRow().getLastCell().getRange().replace("50", "20", options);
        
        doc.save(getArtifactsDir() + "Table.ReplaceCellText.doc");

        Example:

        Shows how to replace text in the document footer.
        // Open the template document, containing obsolete copyright information in the 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.getInstance().get(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.doc");

        Example:

        Simple find and replace operation.
        // Open the document
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        builder.writeln("Hello _CustomerName_,");
        
        // Check the document contains what we are about to test
        System.out.println(doc.getFirstSection().getBody().getParagraphs().get(0).getText());
        
        FindReplaceOptions options = new FindReplaceOptions();
        options.setMatchCase(false);
        options.setFindWholeWordsOnly(false);
        
        // Replace the text in the document
        doc.getRange().replace("_CustomerName_", "James Bond", options);
        
        // Save the modified document
        doc.save(getArtifactsDir() + "Range.ReplaceSimple.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:

                     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
        To leave any meta-character intact a parameter FindReplaceOptions.PreserveMetaCharacters should be set to true.
        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:

        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.doc");
        
        }
        
        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:

        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(Pattern.compile("\\[MY_DOCUMENT\\]"), "", options);
            mainDoc.save(getArtifactsDir() + "InsertDocument.InsertDocumentAtReplace.doc");
        }
        
        private class InsertDocumentAtReplaceHandler implements IReplacingCallback {
            public int replacing(final 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;
            }
        }

        Example:

        Shows how to replace all occurrences of words "sad" or "mad" to "bad".
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.writeln("sad mad bad");
        
        Assert.assertEquals("sad mad bad", doc.getText().trim());
        
        FindReplaceOptions options = new FindReplaceOptions();
        options.setMatchCase(false);
        options.setFindWholeWordsOnly(false);
        
        doc.getRange().replace(Pattern.compile("[s|m]ad"), "bad", options);
        Assert.assertEquals("bad bad bad", 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", 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 range.
        Document doc = new Document(getMyDir() + "Linked fields.docx");
        
        Section newSection = doc.getSections().get(0).deepClone();
        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 document fields in the body of the first section only.
        doc.getFirstSection().getBody().getRange().updateFields();