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();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Hello world!");
Assert.assertEquals("Hello world!", doc.getRange().getText().trim());
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 pattern, java.lang.String replacement) | |
Replaces all occurrences of a character pattern specified by a regular expression 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, 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.
|
public BookmarkCollection getBookmarks()
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; } }
public FieldCollection getFields()
public FormFieldCollection getFormFields()
Example:
Shows how insert different kinds of form fields into a document and process them with a visitor implementation.public void formField() throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Use a document builder to insert a 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()); // Use a document builder to insert a check box 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.writeln(); // Use a document builder to insert text input form field FormField textInput = builder.insertTextInput("MyTextInput", TextFormFieldType.REGULAR, "", "Your text goes here", 50); textInput.setEntryMacro("EntryMacro"); textInput.setExitMacro("ExitMacro"); textInput.setTextInputDefault("Regular"); textInput.setTextInputFormat("FIRST CAPITAL"); textInput.setTextInputValue("This value overrides the one we set during initialization"); Assert.assertEquals(TextFormFieldType.REGULAR, textInput.getTextInputType()); Assert.assertEquals(50, textInput.getMaxLength()); // Get the collection of form fields that has accumulated in our document FormFieldCollection formFields = doc.getRange().getFormFields(); Assert.assertEquals(3, formFields.getCount()); // Our form fields are represented as fields, with field codes FORMDROPDOWN, FORMCHECKBOX and FORMTEXT respectively, // made visible by pressing Alt + F9 in Microsoft Word // These fields have no switches and the content of their form fields is fully governed by members of the FormField object Assert.assertEquals(3, doc.getRange().getFields().getCount()); // Iterate over the collection with an enumerator, accepting a visitor with each form field 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() + "Field.FormField.docx"); } /// <summary> /// Visitor implementation that prints information about visited form fields. /// </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 StringBuilder mBuilder; }
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(); DocumentBuilder builder = new DocumentBuilder(doc); builder.write("Hello world!"); Assert.assertEquals("Hello world!", doc.getRange().getText().trim());
public void delete()
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());
public void normalizeFieldTypes()
Use this method after document changes that affect field types.
To change field type values in the whole document use
public int replace(java.lang.String pattern, java.lang.String replacement) throws java.lang.Exception
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:pattern
- A string to be replaced.replacement
- A string to replace all occurrences of pattern.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());
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.
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:pattern
- A string to be replaced.replacement
- A string to replace all occurrences of pattern.options
- 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.docx");
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 = new Date().getYear(); 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:
Simple find and replace operation.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); doc.getRange().replace("_CustomerName_", "James Bond", options); 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());
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.
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:pattern
- A regular expression pattern used to find matches.replacement
- A string to replace all occurrences of pattern.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");
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.
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:pattern
- A regular expression pattern used to find matches.replacement
- A string to replace all occurrences of pattern.options
- 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; }
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());
public Document toDocument() throws java.lang.Exception
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 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();
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:
Shows how to update document fields in the body of the first section only.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a field that will display the value in the document's body text FieldDocProperty field = (FieldDocProperty) builder.insertField(" DOCPROPERTY Category"); // Set the value of the property that should be displayed by the field doc.getBuiltInDocumentProperties().setCategory("MyCategory"); // Some field types need to be explicitly updated before they can display their expected values Assert.assertEquals("", field.getResult()); // Update all the fields in the first section of the document, which includes the field we just inserted doc.getFirstSection().getRange().updateFields(); Assert.assertEquals("MyCategory", field.getResult());