java.lang.Objectcom.aspose.words.Range
public class Range
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:
Document doc = new Document(getMyDir() + "Document.doc");
String text = doc.getRange().getText();
Property Getters/Setters Summary | ||
---|---|---|
BookmarkCollection | getBookmarks() | |
Returns a |
||
FieldCollection | getFields() | |
Returns a |
||
FormFieldCollection | getFormFields() | |
Returns a |
||
java.lang.String | getText() | |
Gets the text of the range. |
Method Summary | ||
---|---|---|
void | delete() | |
Deletes all characters of the range. | ||
void | normalizeFieldTypes() | |
Changes field type values |
||
int | replace(java.lang.String oldValue, java.lang.String newValue, boolean isMatchCase, boolean isMatchWholeWord) | |
Replaces all occurrences of a specified string with another string. | ||
int | replace(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. | ||
int | replace(java.util.regex.Pattern pattern, IReplacingCallback handler, boolean isForward) | |
Finds all occurrences of a character pattern specified by a regular expression and calls a user defined replace evaluator method. | ||
int | replace(java.util.regex.Pattern pattern, java.lang.String replacement) | |
Replaces all occurrences of a character pattern specified by a regular expression with another string. | ||
int | replace(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. | ||
Document | toDocument() | |
Constructs a new fully formed document that contains the range. | ||
void | unlinkFields() | |
Unlinks fields in this range. | ||
void | updateFields() | |
Updates the values of document fields in this range. |
Property Getters/Setters Detail |
---|
getBookmarks | |
public BookmarkCollection getBookmarks() |
Example:
Shows how to get or set bookmark name and text.Document doc = new Document(getMyDir() + "Bookmark.doc"); // Use the indexer of the Bookmarks collection to obtain the desired bookmark. Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark"); // Get the name and text of the bookmark. String name = bookmark.getName(); String text = bookmark.getText(); // Set the name and text of the bookmark. bookmark.setName("RenamedBookmark"); bookmark.setText("This is a new bookmarked text.");
getFields | |
public FieldCollection getFields() |
getFormFields | |
public FormFieldCollection getFormFields() |
Example:
Shows how to get a collection of form fields.Document doc = new Document(getMyDir() + "FormFields.doc"); FormFieldCollection formFields = doc.getRange().getFormFields();
getText | |
public java.lang.String getText() |
The returned string includes all control and special characters as described in
Example:
Shows how to get plain, unformatted text of a range.Document doc = new Document(getMyDir() + "Document.doc"); String text = doc.getRange().getText();
Method Detail |
---|
delete | |
public void delete() |
Example:
Shows how to delete all characters of a range.// Open Word document. Document doc = new Document(getMyDir() + "Range.DeleteSection.doc"); // The document contains two sections. Each section has a paragraph of text. System.out.println(doc.getText()); // 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. System.out.println(doc.getText());
normalizeFieldTypes | |
public void normalizeFieldTypes() |
Use this method after document changes that affect field types.
To change field type values in the whole document use
replace | |
public int replace(java.lang.String oldValue, java.lang.String newValue, boolean isMatchCase, boolean isMatchWholeWord) throws java.lang.Exception |
An exception is thrown if a captured or replacement string contain one or more special characters: paragraph break, cell break, section break, field start, field separator, field end, inline picture, drawing object, footnote.
oldValue
- A string to be replaced.newValue
- A string to replace all occurrences of oldValue.isMatchCase
- True indicates case-sensitive comparison, false indicates case-insensitive comparision.isMatchWholeWord
- True indicates the oldValue must be a standalone word.replace | |
public int replace(java.lang.String pattern, java.lang.String replacement, FindReplaceOptions options) throws java.lang.Exception |
Replaces the whole match captured by the regular expression.
This is an advanced version of replace method and it's able to process breaks in both pattern and replacement strings.
You should use special meta-characters if you need to work with breaks:pattern
- A string to be replaced.replacement
- A string to replace all occurrences of pattern.options
- Example:
Show changes for headers and footers orderDocument doc = new Document(getMyDir() + "HeaderFooter.HeaderFooterOrder.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); 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 /*ReplaceAction*/int replacing(ReplacingArgs e) { _textBuilder.append(e.getMatchNode().getText() + "\r\n"); return ReplaceAction.SKIP; } void clearText() { _textBuilder.setLength(0); } String getText() { return _textBuilder.toString(); } private /*final*/ StringBuilder _textBuilder = new StringBuilder(); }
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() + "HeaderFooter.ReplaceText.doc"); HeaderFooterCollection headersFooters = doc.getFirstSection().getHeadersFooters(); HeaderFooter footer = headersFooters.getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY); FindReplaceOptions options = new FindReplaceOptions(); options.setMatchCase(false); options.setFindWholeWordsOnly(false); footer.getRange().replace("(C) 2006 Aspose Pty Ltd.", "Copyright (C) 2011 by Aspose Pty Ltd.", options); doc.save(getMyDir() + "\\Artifacts\\HeaderFooter.ReplaceText.doc");
Example:
Shows how to replace all instances of string of text in a table and cell.Document doc = new Document(getMyDir() + "Table.SimpleTable.doc"); // Get the first table in the document. Table table = (Table) doc.getChild(NodeType.TABLE, 0, true); 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(getMyDir() + "\\Artifacts\\Table.ReplaceCellText.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(getMyDir() + "\\Artifacts\\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, IReplacingCallback handler, boolean isForward) throws java.lang.Exception |
An exception is thrown if a captured or replacement string contain one or more special characters: paragraph break, cell break, section break, field start, field separator, field end, inline picture, drawing object, footnote.
pattern
- A regular expression pattern used to find matches.handler
- The user-defined method which evaluates replacement at each step.isForward
- True to replace from the beginning of the range to the end.replace | |
public int replace(java.util.regex.Pattern pattern, java.lang.String replacement) throws java.lang.Exception |
Replaces the whole match captured by the regular expression.
An exception is thrown if a captured or replacement string contain one or more special characters: paragraph break, cell break, section break, field start, field separator, field end, inline picture, drawing object, footnote.
pattern
- A regular expression pattern used to find matches.replacement
- A string to replace all occurrences of oldValue.replace | |
public int replace(java.util.regex.Pattern pattern, java.lang.String replacement, FindReplaceOptions options) throws java.lang.Exception |
Replaces the whole match captured by the regular expression.
This is an advanced version of replace method and it's able to process breaks in both pattern and replacement strings.
You should use special meta-characters if you need to work with breaks:pattern
- A regular expression pattern used to find matches.replacement
- A string to replace all occurrences of pattern.options
- 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(getMyDir() + "\\Artifacts\\Range.ReplaceWithInsertHtml.doc"); } private class ReplaceWithHtmlEvaluator implements IReplacingCallback { ReplaceWithHtmlEvaluator(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(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 /*final*/ 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() + "InsertDocument1.doc"); FindReplaceOptions options = new FindReplaceOptions(); options.setDirection(FindReplaceDirection.BACKWARD); options.setReplacingCallback(new InsertDocumentAtReplaceHandler()); mainDoc.getRange().replace(Pattern.compile("\\[MY_DOCUMENT\\]"), "", options); mainDoc.save(getMyDir() + "\\Artifacts\\InsertDocumentAtReplace.doc"); } private class InsertDocumentAtReplaceHandler implements IReplacingCallback { public int replacing(ReplacingArgs e) throws Exception { Document subDoc = new Document(getMyDir() + "InsertDocument2.doc"); // Insert a document after the paragraph, containing the match text. Paragraph para = (Paragraph) e.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(getMyDir() + "Document.doc"); FindReplaceOptions options = new FindReplaceOptions(); options.setMatchCase(false); options.setFindWholeWordsOnly(false); doc.getRange().replace(Pattern.compile("[s|m]ad"), "bad", options);
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 |
unlinkFields | |
public void unlinkFields() throws java.lang.Exception |
Replaces all the fields in this range with their most recent results.
To unlink fields in the whole document use
Example:
Shows how to unlink all fields in rangeDocument doc = new Document(getMyDir() + "Field.UnlinkFields.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 |
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
To update fields in the whole document use
Example:
Demonstrates how to update document fields in the body of the first section only.doc.getFirstSection().getBody().getRange().updateFields();