com.aspose.words

Class Document

  • All Implemented Interfaces:
    java.lang.Iterable, java.lang.Cloneable
    public class Document 
    extends DocumentBase

Represents a Word document.

The Document is a central object in the Aspose.Words library.

To load an existing document in any of the LoadFormat formats, pass a file name or a stream into one of the Document constructors. To create a blank document, call the constructor without parameters.

Use one of the Save method overloads to save the document in any of the SaveFormat formats.

To draw document pages directly onto a Graphics object use renderToScale(int,java.awt.Graphics2D,float,float,float) or renderToSize(int,java.awt.Graphics2D,float,float,float,float) method.

To print the document, use one of the print(java.lang.String) methods.

MailMerge is the Aspose.Words's reporting engine that allows to populate reports designed in Microsoft Word with data from various data sources quickly and easily. The data can be from a java.sql.ResultSet or an array of values. MailMerge will go through the records found in the data source and insert them into mail merge fields in the document growing it as necessary.

Document stores document-wide information such as Styles, BuiltInDocumentProperties, CustomDocumentProperties, lists and macros. Most of these objects are accessible via the corresponding properties of the Document.

The Document is a root node of a tree that contains all other nodes of the document. The tree is a Composite design pattern and in many ways similar to XmlDocument. The content of the document can be manipulated freely programmatically:

Consider using DocumentBuilder that simplifies the task of programmatically creating or populating the document tree.

The Document can contain only Section objects.

In Microsoft Word, a valid document needs to have at least one section.

Example:

Converts a whole document from DOC to PDF using default options.
Document doc = new Document(getMyDir() + "Document.doc");

doc.save(getMyDir() + "\\Artifacts\\Document.Doc2PdfSave.pdf");

Example:

Executes mail merge from data stored in a ResultSet.
Document doc = new Document(getMyDir() + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database. 
DataTable table = new DataTable("Test");
table.getColumns().add("CustomerName");
table.getColumns().add("Address");
table.getRows().add(new Object[] { "Thomas Hardy", "120 Hanover Sq., London" });
table.getRows().add(new Object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });

// Field values from the table are inserted into the mail merge fields found in the document.
doc.getMailMerge().execute(table);

doc.save(getMyDir() + "\\Artifacts\\MailMerge.ExecuteDataTable.doc");

Constructor Summary
Document()
Creates a blank Word document.
Document(java.lang.StringfileName)
Opens an existing document from a file. Automatically detects the file format.
Document(java.lang.StringfileName, LoadOptions loadOptions)
Opens an existing document from a file. Allows to specify additional options such as an encryption password.
Document(java.io.InputStreamstream)
Opens an existing document from a stream. Automatically detects the file format.
Document(java.io.InputStreamstream, LoadOptions loadOptions)
Opens an existing document from a stream. Allows to specify additional options such as an encryption password.
 
Property Getters/Setters Summary
java.lang.StringgetAttachedTemplate()
void
setAttachedTemplate(java.lang.Stringvalue)
           Gets or sets the full path of the template attached to the document.
booleangetAutomaticallyUpdateSyles()
void
           Gets or sets a flag indicating whether the styles in the document are updated to match the styles in the attached template each time the document is opened in MS Word.
ShapegetBackgroundShape()
void
           Gets or sets the background shape of the document. Can be null.
BuiltInDocumentPropertiesgetBuiltInDocumentProperties()
Returns a collection that represents all the built-in document properties of the document.
NodeCollectiongetChildNodes()
Gets all immediate child nodes of this node.
CompatibilityOptionsgetCompatibilityOptions()
Provides access to document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).
intgetCompliance()
Gets the OOXML compliance version determined from the loaded document content. Makes sense only for OOXML documents. The value of the property is OoxmlCompliance integer constant.
intgetCount()
Gets the number of immediate children of this node.
CustomDocumentPropertiesgetCustomDocumentProperties()
Returns a collection that represents all the custom document properties of the document.
CustomXmlPartCollectiongetCustomXmlParts()
void
           Gets or sets the collection of Custom XML Data Storage Parts.
doublegetDefaultTabStop()
void
setDefaultTabStop(doublevalue)
           Gets or sets the interval (in points) between the default tab stops.
DigitalSignatureCollectiongetDigitalSignatures()
Gets the collection of digital signatures for this document and their validation results.
DocumentBasegetDocument()
Gets the document to which this node belongs.
EndnoteOptionsgetEndnoteOptions()
Provides options that control numbering and positioning of endnotes in this document.
FieldOptionsgetFieldOptions()
Gets a FieldOptions object that represents options to control field handling in the document.
NodegetFirstChild()
Gets the first child of the node.
SectiongetFirstSection()
Gets the first section in the document.
FontInfoCollectiongetFontInfos()
Provides access to properties of fonts used in this document.
FontSettingsgetFontSettings()
void
           Gets or sets document font settings.
FootnoteOptionsgetFootnoteOptions()
Provides options that control numbering and positioning of footnotes in this document.
GlossaryDocumentgetGlossaryDocument()
void
           Gets or sets the glossary document within this document or template. A glossary document is a storage for AutoText, AutoCorrect and Building Block entries defined in a document.
booleanhasChildNodes()
Returns true if this node has any child nodes.
booleanhasMacros()
Returns true if the document has a VBA project (macros).
booleanhasRevisions()
Returns true if the document has any tracked changes.
HyphenationOptionsgetHyphenationOptions()
Provides access to document hyphenation options.
booleanisComposite()
Returns true as this node can have child nodes.
NodegetLastChild()
Gets the last child of the node.
SectiongetLastSection()
Gets the last section in the document.
LayoutOptionsgetLayoutOptions()
Gets a LayoutOptions object that represents options to control the layout process of this document.
ListCollectiongetLists()
Provides access to the list formatting used in the document.
MailMergegetMailMerge()
Returns a MailMerge object that represents the mail merge functionality for the document.
MailMergeSettingsgetMailMergeSettings()
void
           Gets or sets the object that contains all of the mail merge information for a document.
NodegetNextSibling()
Gets the node immediately following this node.
INodeChangingCallbackgetNodeChangingCallback()
void
           Called when a node is inserted or removed in the document.
intgetNodeType()
Returns NodeType.Document. The value of the property is NodeType integer constant.
java.lang.StringgetOriginalFileName()
Gets the original file name of the document.
intgetOriginalLoadFormat()
Gets the format of the original document that was loaded into this object. The value of the property is LoadFormat integer constant.
CustomPartCollectiongetPackageCustomParts()
void
           Gets or sets the collection of custom parts (arbitrary content) that are linked to the OOXML package using "unknown relationships".
java.awt.ColorgetPageColor()
void
setPageColor(java.awt.Colorvalue)
           Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.
intgetPageCount()
Gets the number of pages in the document as calculated by the most recent page layout operation.
CompositeNodegetParentNode()
Gets the immediate parent of this node.
NodegetPreviousSibling()
Gets the node immediately preceding this node.
intgetProtectionType()
Gets the currently active document protection type. The value of the property is ProtectionType integer constant.
RangegetRange()
Returns a Range object that represents the portion of a document that is contained in this node.
booleangetRemovePersonalInformation()
void
           Gets or sets a flag indicating that Microsoft Word will remove all user information from comments, revisions and document properties upon saving the document.
IResourceLoadingCallbackgetResourceLoadingCallback()
void
           Allows to control how external resources are loaded.
RevisionCollectiongetRevisions()
Gets a collection of revisions (tracked changes) that exist in this document.
SectionCollectiongetSections()
Returns a collection that represents all sections in the document.
booleangetShadeFormData()
void
setShadeFormData(booleanvalue)
           Specifies whether to turn on the gray shading on form fields.
StyleCollectiongetStyles()
Returns a collection of styles defined in the document.
ThemegetTheme()
Gets the Theme object for this document.
booleangetTrackRevisions()
void
setTrackRevisions(booleanvalue)
          True if changes are tracked when this document is edited in Microsoft Word.
VariableCollectiongetVariables()
Returns the collection of variables added to a document or template.
intgetVersionsCount()
Gets the number of document versions that was stored in the DOC document.
ViewOptionsgetViewOptions()
Provides options to control how the document is displayed in Microsoft Word.
IWarningCallbackgetWarningCallback()
void
           Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.
WriteProtectiongetWriteProtection()
Provides access to the document write protection options.
 
Method Summary
booleanaccept(DocumentVisitor visitor)
Accepts a visitor.
voidacceptAllRevisions()
Accepts all tracked changes in the document.
NodeappendChild(Node newChild)
Adds the specified node to the end of the list of child nodes for this node.
voidappendDocument(Document srcDoc, int importFormatMode)
Appends the specified document to the end of this document.
voidcleanup()
Cleans unused styles and lists from the document.
voidcleanup(CleanupOptions options)
Cleans unused styles and lists from the document depending on given CleanupOptions.
voidcompare(Document document, java.lang.String author, java.util.Date dateTime)
Compares this document with another document producing changes as number of edit and format revisions Revision.
voidcompare(Document document, java.lang.String author, java.util.Date dateTime, CompareOptions options)
Compares this document with another document producing changes as a number of edit and format revisions Revision. Allows to specify comparison options using CompareOptions.
voidcopyStylesFromTemplate(Document template)
Copies styles from the specified template to a document.
voidcopyStylesFromTemplate(java.lang.String template)
Copies styles from the specified template to a document.
DocumentdeepClone()
Performs a deep copy of the Document.
NodedeepClone(boolean isCloneChildren)
voidensureMinimum()
If the document contains no sections, creates one section with one paragraph.
voidexpandTableStylesToDirectFormatting()
Converts formatting specified in table styles into direct formatting on tables in the document.
CompositeNodegetAncestor(int ancestorType)
Gets the first ancestor of the specified NodeType.
CompositeNodegetAncestor(java.lang.Class ancestorType)
Gets the first ancestor of the specified object type.
NodegetChild(int nodeType, int index, boolean isDeep)
Returns an Nth child node that matches the specified type.
NodeCollectiongetChildNodes(int nodeType, boolean isDeep)
Returns a live collection of child nodes that match the specified type.
PageInfogetPageInfo(int pageIndex)
Gets the page size, orientation and other information about a page that might be useful for printing or rendering.
java.lang.StringgetText()
Gets the text of this node and of all its children.
NodeimportNode(Node srcNode, boolean isImportChildren)

Imports a node from another document to the current document.

NodeimportNode(Node srcNode, boolean isImportChildren, int importFormatMode)

Imports a node from another document to the current document with an option to control formatting.

intindexOf(Node child)
Returns the index of the specified child node in the child node array.
NodeinsertAfter(Node newChild, Node refChild)
Inserts the specified node immediately after the specified reference node.
NodeinsertBefore(Node newChild, Node refChild)
Inserts the specified node immediately before the specified reference node.
java.util.Iterator<Node>iterator()
Provides support for the for each style iteration over the child nodes of this node.
intjoinRunsWithSameFormatting()
Joins runs with same formatting in all paragraphs of the document.
NodenextPreOrder(Node rootNode)
Gets next node according to the pre-order tree traversal algorithm.
voidnormalizeFieldTypes()
Changes field type values FieldChar.FieldType of FieldStart, FieldSeparator, FieldEnd in the whole document so that they correspond to the field types contained in the field codes.
NodeprependChild(Node newChild)
Adds the specified node to the beginning of the list of child nodes for this node.
NodepreviousPreOrder(Node rootNode)
Gets the previous node according to the pre-order tree traversal algorithm.
voidprint()
Prints the whole document to the default printer.
voidprint(java.lang.String printerName)
Print the whole document to the specified printer, using the standard (no User Interface) print controller.
voidprint(javax.print.attribute.AttributeSet printerSettings)
Prints the document according to the specified printer settings, using the standard (no User Interface) print controller.
voidprint(javax.print.attribute.AttributeSet printerSettings, java.lang.String documentName)
Prints the document according to the specified printer settings, using the standard (no User Interface) print controller and a document name.
voidprotect(int type)
Protects the document from changes without changing the existing password or assigns a random password.
voidprotect(int type, java.lang.String password)
Protects the document from changes and optionally sets a protection password.
voidremove()
Removes itself from the parent.
voidremoveAllChildren()
Removes all the child nodes of the current node.
NoderemoveChild(Node oldChild)
Removes the specified child node.
voidremoveExternalSchemaReferences()
Removes external XML schema references from this document.
voidremoveMacros()
Removes all macros (the VBA project) as well as toolbars and command customizations from the document.
voidremoveSmartTags()
Removes all SmartTag descendant nodes of the current node.
java.awt.geom.Point2D.FloatrenderToScale(int pageIndex, java.awt.Graphics2D graphics, float x, float y, float scale)
Renders a document page into a java.awt.Graphics2D object to a specified scale.
floatrenderToSize(int pageIndex, java.awt.Graphics2D graphics, float x, float y, float width, float height)
voidsave(java.io.OutputStream outputStream, SaveOptions saveOptions)
Saves the document to a stream using the specified save options.
voidsave(java.io.OutputStream outputStream, int saveFormat)
Saves the document to a stream using the specified format.
SaveOutputParameterssave(java.lang.String fileName)
Saves the document to a file. Automatically determines the save format from the extension.
SaveOutputParameterssave(java.lang.String fileName, SaveOptions saveOptions)
Saves the document to a file using the specified save options.
SaveOutputParameterssave(java.lang.String fileName, int saveFormat)
Saves the document to a file in the specified format.
NodeListselectNodes(java.lang.String xpath)
Selects a list of nodes matching the XPath expression.
NodeselectSingleNode(java.lang.String xpath)
Selects the first Node that matches the XPath expression.
voidstartTrackRevisions(java.lang.String author)
Starts automatically marking all further changes you make to the document programmatically as revision changes.
voidstartTrackRevisions(java.lang.String author, java.util.Date dateTime)
Starts automatically marking all further changes you make to the document programmatically as revision changes.
voidstopTrackRevisions()
Stops automatic marking of document changes as revisions.
java.lang.StringtoString(SaveOptions saveOptions)
Exports the content of the node into a string using the specified save options.
java.lang.StringtoString(int saveFormat)
Exports the content of the node into a string in the specified format.
voidunlinkFields()
Unlinks fields in the whole document.
voidunprotect()
Removes protection from the document regardless of the password.
booleanunprotect(java.lang.String password)
Removes protection from the document if a correct password is specified.
voidupdateFields()
Updates the values of fields in the whole document.
voidupdateListLabels()
Updates list labels for all list items in the document.
voidupdatePageLayout()
Rebuilds the page layout of the document.
voidupdateTableLayout()
Updates widths of cells and tables in the document according to their preferred widths and content. You do not need to call this method if the tables appear correct in the output document.
voidupdateThumbnail()
Updates BuiltInDocumentProperties.Thumbnail of the document using default options.
voidupdateThumbnail(ThumbnailGeneratingOptions options)
Updates BuiltInDocumentProperties.Thumbnail of the document according to the specified options.
voidupdateWordCount()
Updates word count properties of the document.
voidupdateWordCount(boolean updateLinesCount)
Updates word count properties of the document, optionally updates BuiltInDocumentProperties.Lines property.
 

    • Constructor Detail

      • Document

        public Document()
                 throws java.lang.Exception
        Creates a blank Word document.

        The document paper size is Letter by default. If you want to change page setup, use Section.PageSetup.

        After creation, you can use DocumentBuilder to add document content easily.

        Example:

        Shows how to add a formatted run of text to a document using the object model.
        // Create an empty document. It contains one empty paragraph.
        Document doc = new Document();
        
        // Create a new run of text.
        Run run = new Run(doc, "Hello");
        
        // Specify character formatting for the run of text.
        Font f = run.getFont();
        f.setName("Courier New");
        f.setSize(36);
        f.setHighlightColor(Color.YELLOW);
        
        // Append the run of text to the end of the first paragraph
        // in the body of the first section of the document.
        doc.getFirstSection().getBody().getFirstParagraph().appendChild(run);
      • Document

        public Document(java.lang.String fileName)
                 throws java.lang.Exception
        Opens an existing document from a file. Automatically detects the file format.
        Parameters:
        fileName - File name of the document to open.

        Example:

        Opens a document from a file.
        // Open a document. The file is opened read only and only for the duration of the constructor.
        Document doc = new Document(getMyDir() + "Document.doc");
      • Document

        public Document(java.lang.String fileName, LoadOptions loadOptions)
                 throws java.lang.Exception
        Opens an existing document from a file. Allows to specify additional options such as an encryption password.
        Parameters:
        fileName - File name of the document to open.
        loadOptions - Additional options to use when loading a document. Can be null.

        Example:

        Explicitly loads a document as HTML without automatic file format detection.
        LoadOptions loadOptions = new LoadOptions();
        loadOptions.setLoadFormat(com.aspose.words.LoadFormat.HTML);
        Document doc = new Document(getMyDir() + "Document.LoadFormat.html", loadOptions);

        Example:

        Loads a Microsoft Word document encrypted with a password.
        Document doc = new Document(getMyDir() + "Document.LoadEncrypted.doc", new LoadOptions("qwerty"));
      • Document

        public Document(java.io.InputStream stream)
                 throws java.lang.Exception
        Opens an existing document from a stream. Automatically detects the file format.

        The document must be stored at the beginning of the stream.

        Parameters:
        stream - Stream where to load the document from.

        Example:

        Retrieves a document from a URL and saves it to disk in a different format.
        // This is the URL pointing to where to find the document.
        URL url = new URL("http://www.aspose.com/demos/.net-components/aspose.words/csharp/general/Common/Documents/DinnerInvitationDemo.doc");
        
        // The easiest way to load our document from the internet is make use of the URLConnection class.
        URLConnection webClient = url.openConnection();
        
        // Download the bytes from the location referenced by the URL.
        InputStream inputStream = webClient.getInputStream();
        
        // Convert the input stream to a byte array.
        int pos;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((pos = inputStream.read()) != -1) bos.write(pos);
        
        byte[] dataBytes = bos.toByteArray();
        
        // Wrap the bytes representing the document in memory into a stream object.
        ByteArrayInputStream byteStream = new ByteArrayInputStream(dataBytes);
        
        // Load this memory stream into a new Aspose.Words Document.
        // The file format of the passed data is inferred from the content of the bytes itself.
        // You can load any document format supported by Aspose.Words in the same way.
        Document doc = new Document(byteStream);
        
        // Convert the document to any format supported by Aspose.Words.
        doc.save(getMyDir() + "\\Artifacts\\Document.OpenFromWeb.docx");

        Example:

        Opens a document from a stream.
        // Open the stream. Read only access is enough for Aspose.Words to load a document.
        InputStream stream = new FileInputStream(getMyDir() + "Document.doc");
        
        // Load the entire document into memory.
        Document doc = new Document(stream);
        
        // You can close the stream now, it is no longer needed because the document is in memory.
        stream.close();
        
        // ... do something with the document
      • Document

        public Document(java.io.InputStream stream, LoadOptions loadOptions)
                 throws java.lang.Exception
        Opens an existing document from a stream. Allows to specify additional options such as an encryption password.

        The document must be stored at the beginning of the stream.

        Parameters:
        stream - The stream where to load the document from.
        loadOptions - Additional options to use when loading a document. Can be null.

        Example:

        Shows how to insert the HTML contents from a web page into a new document.
        // The url of the page to load
        URL url = new URL("http://www.aspose.com/");
        
        // The easiest way to load our document from the internet is make use of the URLConnection class.
        URLConnection webClient = url.openConnection();
        
        // Download the bytes from the location referenced by the URL.
        InputStream inputStream = webClient.getInputStream();
        
        // Convert the input stream to a byte array.
        int pos;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((pos = inputStream.read()) != -1) bos.write(pos);
        
        byte[] dataBytes = bos.toByteArray();
        
        // Wrap the bytes representing the document in memory into a stream object.
        ByteArrayInputStream byteStream = new ByteArrayInputStream(dataBytes);
        
        // The baseUri property should be set to ensure any relative img paths are retrieved correctly.
        LoadOptions options = new LoadOptions(LoadFormat.HTML, "", url.getPath());
        
        // Load the HTML document from stream and pass the LoadOptions object.
        Document doc = new Document(byteStream, options);
        
        // Save the document to disk.
        // The extension of the filename can be changed to save the document into other formats. e.g PDF, DOCX, ODT, RTF.
        doc.save(getMyDir() + "\\Artifacts\\Document.HtmlPageFromWebpage.doc");

        Example:

        Opens an HTML document with images from a stream using a base URI.
        // We are opening this HTML file:
        //    <html>
        //    <body>
        //    <p>Simple file.</p>
        //    <p><img src="Aspose.Words.gif" width="80" height="60"></p>
        //    </body>
        //    </html>
        String fileName = getMyDir() + "Document.OpenFromStreamWithBaseUri.html";
        
        // Open the stream.
        InputStream stream = new FileInputStream(fileName);
        
        // Open the document. Note the Document constructor detects HTML format automatically.
        // Pass the URI of the base folder so any images with relative URIs in the HTML document can be found.
        LoadOptions loadOptions = new LoadOptions();
        loadOptions.setBaseUri(getMyDir());
        Document doc = new Document(stream, loadOptions);
        
        // You can close the stream now, it is no longer needed because the document is in memory.
        stream.close();
        
        // Save in the DOC format.
        doc.save(getMyDir() + "\\Artifacts\\Document.OpenFromStreamWithBaseUri.doc");

        Example:

        Loads a Microsoft Word document encrypted with a password from a stream.
        InputStream stream = new FileInputStream(getMyDir() + "Document.LoadEncrypted.doc");
        Document doc = new Document(stream, new LoadOptions("qwerty"));
        stream.close();
    • Property Getters/Setters Detail

      • getAttachedTemplate/setAttachedTemplate

        public java.lang.String getAttachedTemplate() / public void setAttachedTemplate(java.lang.String value)
        
        Gets or sets the full path of the template attached to the document.

        Empty string means the document is attached to the Normal template.

        Example:

        Opens a document, makes sure it is no longer attached to a template and saves the document.
        Document doc = new Document(getMyDir() + "Document.doc");
        doc.setAttachedTemplate("");
        doc.save(getMyDir() + "\\Artifacts\\Document.DetachTemplate.doc");
        See Also:
        BuiltInDocumentProperties.Template
      • getAutomaticallyUpdateSyles/setAutomaticallyUpdateSyles

        public boolean getAutomaticallyUpdateSyles() / public void setAutomaticallyUpdateSyles(boolean value)
        
        Gets or sets a flag indicating whether the styles in the document are updated to match the styles in the attached template each time the document is opened in MS Word.
      • getBuiltInDocumentProperties

        public BuiltInDocumentProperties getBuiltInDocumentProperties()
        
        Returns a collection that represents all the built-in document properties of the document.

        Example:

        Enumerates through all built-in and custom properties in a document.
        String fileName = getMyDir() + "Properties.doc";
        Document doc = new Document(fileName);
        
        System.out.println(MessageFormat.format("1. Document name: {0}", doc.getOriginalFileName()));
        
        System.out.println("2. Built-in Properties");
        for (DocumentProperty docProperty : doc.getBuiltInDocumentProperties())
            System.out.println(MessageFormat.format("{0} : {1}", docProperty.getName(), docProperty.getValue()));
        
        System.out.println("3. Custom Properties");
        for (DocumentProperty docProperty : doc.getCustomDocumentProperties())
            System.out.println(MessageFormat.format("{0} : {1}", docProperty.getName(), docProperty.getValue()));
      • getChildNodes

        public NodeCollection getChildNodes()
        
        Gets all immediate child nodes of this node.

        Note, ChildNodes is equivalent to calling GetChildNodes(NodeType.Any, false) and creates and returns a new collection every time it is accessed.

        If there are no child nodes, this property returns an empty collection.

        Example:

        Shows how to enumerate immediate children of a CompositeNode using the enumerator provided by the ChildNodes collection.
        NodeCollection children = paragraph.getChildNodes();
        for (Node child : (Iterable<Node>) children)
        {
            // Paragraph may contain children of various types such as runs, shapes and so on.
            if (child.getNodeType() == NodeType.RUN)
            {
                // Say we found the node that we want, do something useful.
                Run run = (Run) child;
                System.out.println(run.getText());
            }
        }
      • getCompatibilityOptions

        public CompatibilityOptions getCompatibilityOptions()
        
        Provides access to document compatibility options (that is, the user preferences entered on the Compatibility tab of the Options dialog in Word).
      • getCompliance

        public int getCompliance()
        
        Gets the OOXML compliance version determined from the loaded document content. Makes sense only for OOXML documents. The value of the property is OoxmlCompliance integer constant.

        If you created a new blank document or load non OOXML document returns the OoxmlCompliance.ECMA_376_2006 value.

        Example:

        Shows how to get OOXML compliance version.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        int compliance = doc.getCompliance();
      • getCount

        public int getCount()
        
        Gets the number of immediate children of this node.
      • getCustomDocumentProperties

        public CustomDocumentProperties getCustomDocumentProperties()
        
        Returns a collection that represents all the custom document properties of the document.

        Example:

        Enumerates through all built-in and custom properties in a document.
        String fileName = getMyDir() + "Properties.doc";
        Document doc = new Document(fileName);
        
        System.out.println(MessageFormat.format("1. Document name: {0}", doc.getOriginalFileName()));
        
        System.out.println("2. Built-in Properties");
        for (DocumentProperty docProperty : doc.getBuiltInDocumentProperties())
            System.out.println(MessageFormat.format("{0} : {1}", docProperty.getName(), docProperty.getValue()));
        
        System.out.println("3. Custom Properties");
        for (DocumentProperty docProperty : doc.getCustomDocumentProperties())
            System.out.println(MessageFormat.format("{0} : {1}", docProperty.getName(), docProperty.getValue()));
      • getCustomXmlParts/setCustomXmlParts

        public CustomXmlPartCollection getCustomXmlParts() / public void setCustomXmlParts(CustomXmlPartCollection value)
        
        Gets or sets the collection of Custom XML Data Storage Parts.

        Aspose.Words loads and saves Custom XML Parts into OOXML and DOC documents only.

        This property cannot be null.

        Example:

        Shows how to create structured document tag with a custom XML data.
        Document doc = new Document();
        // Add test XML data part to the collection.
        CustomXmlPart xmlPart = doc.getCustomXmlParts().add(UUID.randomUUID().toString(), "<root><text>Hello, World!</text></root>");
        
        StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PLAIN_TEXT, MarkupLevel.BLOCK);
        sdt.getXmlMapping().setMapping(xmlPart, "/root[1]/text[1]", "");
        
        doc.getFirstSection().getBody().appendChild(sdt);
        
        doc.save(getMyDir() + "\\Artifacts\\SDT.CustomXml.docx");
        See Also:
        CustomXmlPart
      • getDefaultTabStop/setDefaultTabStop

        public double getDefaultTabStop() / public void setDefaultTabStop(double value)
        
        Gets or sets the interval (in points) between the default tab stops.

        Example:

        Changes default tab positions for the document and inserts text with some tab characters.
        DocumentBuilder builder = new DocumentBuilder();
        
        // Set default tab stop to 72 points (1 inch).
        builder.getDocument().setDefaultTabStop(72);
        
        builder.writeln("Hello" + ControlChar.TAB + "World!");
        builder.writeln("Hello" + ControlChar.TAB_CHAR + "World!");
        See Also:
        TabStopCollection, TabStop
      • getDigitalSignatures

        public DigitalSignatureCollection getDigitalSignatures()
        
        Gets the collection of digital signatures for this document and their validation results.

        This collection contains digital signatures that were loaded from the original document. These digital signatures will not be saved when you save this Document object into a file or stream because saving or converting will produce a document that is different from the original and the original digital signatures will no longer be valid.

        This collection is never null. If the document is not signed, it will contain zero elements.

        Example:

        Shows how to validate all signatures in a document.
        // Load the signed document.
        Document doc = new Document(getMyDir() + "Document.Signed.docx");
        
        if (doc.getDigitalSignatures().isValid()) System.out.println("Signatures belonging to this document are valid");
        else System.out.println("Signatures belonging to this document are NOT valid");

        Example:

        Shows how to validate each signature in a document and display basic information about the signature.
        // Load the document which contains signature.
        Document doc = new Document(getMyDir() + "Document.DigitalSignature.docx");
        
        for (DigitalSignature signature : doc.getDigitalSignatures())
        {
            System.out.println("*** Signature Found ***");
            System.out.println("Is valid: " + signature.isValid());
            System.out.println("Reason for signing: " + signature.getComments()); // This property is available in MS Word documents only.
            System.out.println("Signature type: " + DigitalSignatureType.toString(signature.getSignatureType()));
            System.out.println("Time of signing: " + signature.getSignTime());
            System.out.println("Subject name: " + signature.getSubjectName());
            System.out.println("Issuer name: " + signature.getIssuerName());
            System.out.println();
        }
      • getDocument

        public DocumentBase getDocument()
        
        Gets the document to which this node belongs.

        The node always belongs to a document even if it has just been created and not yet added to the tree, or if it has been removed from the tree.

        Example:

        Shows that when you create any node, it requires a document that will own the node.
        // Open a file from disk.
        Document doc = new Document();
        
        // Creating a new node of any type requires a document passed into the constructor.
        Paragraph para = new Paragraph(doc);
        
        // The new paragraph node does not yet have a parent.
        System.out.println("Paragraph has no parent node: " + (para.getParentNode() == null));
        
        // But the paragraph node knows its document.
        System.out.println("Both nodes' documents are the same: " + (para.getDocument() == doc));
        
        // The fact that a node always belongs to a document allows us to access and modify
        // properties that reference the document-wide data such as styles or lists.
        para.getParagraphFormat().setStyleName("Heading 1");
        
        // Now add the paragraph to the main text of the first section.
        doc.getFirstSection().getBody().appendChild(para);
        
        // The paragraph node is now a child of the Body node.
        System.out.println("Paragraph has a parent node: " + (para.getParentNode() != null));
      • getEndnoteOptions

        public EndnoteOptions getEndnoteOptions()
        
        Provides options that control numbering and positioning of endnotes in this document.
      • getFieldOptions

        public FieldOptions getFieldOptions()
        
        Gets a FieldOptions object that represents options to control field handling in the document.

        Example:

        Shows how to specify where the locale for date formatting during field update and mail merge is chosen from.
        // Set the culture used during field update to the culture used by the field.
        doc.getFieldOptions().setFieldUpdateCultureSource(FieldUpdateCultureSource.FIELD_CODE);
        doc.getMailMerge().execute(new String[]{"Date2"}, new Object[]{new SimpleDateFormat("yyyy/MM/DD").parse("2011/01/01")});
      • getFirstChild

        public Node getFirstChild()
        
        Gets the first child of the node. If there is no first child node, a null is returned.

        Example:

        Shows how to enumerate immediate child nodes of a composite node using NextSibling. In this example we enumerate all paragraphs of a section body.
        // Get the section that we want to work on.
        Section section = doc.getSections().get(0);
        Body body = section.getBody();
        
        // Loop starting from the first child until we reach null.
        for (Node node = body.getFirstChild(); node != null; node = node.getNextSibling())
        {
            // Output the types of the nodes that we come across.
            System.out.println(Node.nodeTypeToString(node.getNodeType()));
        }

        Example:

        Shows how to efficiently visit all direct and indirect children of a composite node.
        public void recurseAllNodes() throws Exception
        {
            // Open a document.
            Document doc = new Document(getMyDir() + "Node.RecurseAllNodes.doc");
        
            // Invoke the recursive function that will walk the tree.
            traverseAllNodes(doc);
        }
        
        /**
         * A simple function that will walk through all children of a specified node recursively
         * and print the type of each node to the screen.
         */
        public void traverseAllNodes(CompositeNode parentNode)
        {
            // This is the most efficient way to loop through immediate children of a node.
            for (Node childNode = parentNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling())
            {
                // Do some useful work.
                System.out.println(Node.nodeTypeToString(childNode.getNodeType()));
        
                // Recurse into the node if it is a composite node.
                if (childNode.isComposite()) traverseAllNodes((CompositeNode) childNode);
            }
        }
      • getFirstSection

        public Section getFirstSection()
        
        Gets the first section in the document. Returns null if there are no sections.

        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 you can enumerate through children of a composite node and detect types of the children nodes.
        // Open a document.
        Document doc = new Document(getMyDir() + "Section.BodyNodeType.doc");
        
        // Get the first section in the document.
        Section section = doc.getFirstSection();
        
        // A Section is a composite node and therefore can contain child nodes.
        // Section can contain only Body and HeaderFooter nodes.
        for (Node node : section)
        {
            // Every node has the NodeType property.
            switch (node.getNodeType())
            {
                case NodeType.BODY:
                {
                    // If the node type is Body, we can cast the node to the Body class.
                    Body body = (Body) node;
        
                    // Write the content of the main story of the section to the console.
                    System.out.println("*** Body ***");
                    System.out.println(body.getText());
                    break;
                }
                case NodeType.HEADER_FOOTER:
                {
                    // If the node type is HeaderFooter, we can cast the node to the HeaderFooter class.
                    HeaderFooter headerFooter = (HeaderFooter) node;
        
                    // Write the content of the header footer to the console.
                    System.out.println("*** HeaderFooter ***");
                    System.out.println(headerFooter.getHeaderFooterType());
                    System.out.println(headerFooter.getText());
                    break;
                }
                default:
                {
                    // Other types of nodes never occur inside a Section node.
                    throw new Exception("Unexpected node type in a section.");
                }
            }
        }
      • getFontInfos

        public FontInfoCollection getFontInfos()
        
        Provides access to properties of fonts used in this document.

        This collection of font definitions is loaded as is from the document. Font definitions might be optional, missing or incomplete in some documents.

        Do not rely on this collection to ascertain that a particular font is used in the document. You should only use this collection to get information about fonts that might be used in the document.

        Example:

        Shows how to save a document with embedded TrueType fonts
        Document doc = new Document(getMyDir() + "Document.docx");
        
        FontInfoCollection fontInfos = doc.getFontInfos();
        fontInfos.setEmbedTrueTypeFonts(true);
        fontInfos.setEmbedSystemFonts(false);
        fontInfos.setSaveSubsetFonts(false);
        
        doc.save(getMyDir() + "/Artifacts/Document.docx");

        Example:

        Shows how to gather the details of what fonts are present in a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        FontInfoCollection fonts = doc.getFontInfos();
        int fontIndex = 1;
        
        // The fonts info extracted from this document does not necessarily mean that the fonts themselves are
        // used in the document. If a font is present but not used then most likely they were referenced at some time
        // and then removed from the Document.
        for (FontInfo info : fonts)
        {
            // Print out some important details about the font.
            System.out.println(MessageFormat.format("Font #{0}", fontIndex));
            System.out.println(MessageFormat.format("Name: {0}", info.getName()));
            System.out.println(MessageFormat.format("IsTrueType: {0}", info.isTrueType()));
            fontIndex++;
        }
        See Also:
        FontInfoCollection, FontInfo
      • getFontSettings/setFontSettings

        public FontSettings getFontSettings() / public void setFontSettings(FontSettings value)
        
        Gets or sets document font settings.

        This property allows to specify font settings per document. If set to null, default static font settings FontSettings.DefaultInstance will be used.

        The default value is null.

        Example:

        Shows how to define alternative fonts if original does not exist
        FontSettings fontSettings = new FontSettings();
        fontSettings.setFontSubstitutes("Times New Roman","Slab", "Arvo" );
      • getFootnoteOptions

        public FootnoteOptions getFootnoteOptions()
        
        Provides options that control numbering and positioning of footnotes in this document.

        Example:

        Shows how to add a footnote to a paragraph in the document using DocumentBuilder.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        for (int i = 0; i <= 100; i++)
        {
            builder.write("Some text " + i);
        
            builder.insertFootnote(FootnoteType.FOOTNOTE, "Footnote text " + i);
            builder.insertFootnote(FootnoteType.FOOTNOTE, "Footnote text " + i, "242");
        }
      • getGlossaryDocument/setGlossaryDocument

        public GlossaryDocument getGlossaryDocument() / public void setGlossaryDocument(GlossaryDocument value)
        
        Gets or sets the glossary document within this document or template. A glossary document is a storage for AutoText, AutoCorrect and Building Block entries defined in a document.

        This property returns null if the document does not have a glossary document.

        You can add a glossary document to a document by creating a GlossaryDocument object and assigning to this property.

        See Also:
        GlossaryDocument
      • hasChildNodes

        public boolean hasChildNodes()
        
        Returns true if this node has any child nodes.

        Example:

        Demonstrates how to use the InsertDocument method to insert a document into a merge field during mail merge.
        public void insertDocumentAtMailMerge() throws Exception
        {
            // Open the main document.
            Document mainDoc = new Document(getMyDir() + "InsertDocument1.doc");
        
            // Add a handler to MergeField event
            mainDoc.getMailMerge().setFieldMergingCallback(new InsertDocumentAtMailMergeHandler());
        
            // The main document has a merge field in it called "Document_1".
            // The corresponding data for this field contains fully qualified path to the document
            // that should be inserted to this field.
            mainDoc.getMailMerge().execute(new String[]{"Document_1"}, new String[]{getMyDir() + "InsertDocument2.doc"});
        
            mainDoc.save(getMyDir() + "\\Artifacts\\InsertDocumentAtMailMerge.doc");
        }
        
        private class InsertDocumentAtMailMergeHandler implements IFieldMergingCallback
        {
            /**
             * This handler makes special processing for the "Document_1" field.
             * The field value contains the path to load the document.
             * We load the document and insert it into the current merge field.
             */
            public void fieldMerging(FieldMergingArgs args) throws Exception
            {
                if ("Document_1".equals(args.getDocumentFieldName()))
                {
                    // Use document builder to navigate to the merge field with the specified name.
                    DocumentBuilder builder = new DocumentBuilder(args.getDocument());
                    builder.moveToMergeField(args.getDocumentFieldName());
        
                    // The name of the document to load and insert is stored in the field value.
                    Document subDoc = new Document((String) args.getFieldValue());
        
                    // Insert the document.
                    insertDocument(builder.getCurrentParagraph(), subDoc);
        
                    // The paragraph that contained the merge field might be empty now and you probably want to delete it.
                    if (!builder.getCurrentParagraph().hasChildNodes()) builder.getCurrentParagraph().remove();
        
                    // Indicate to the mail merge engine that we have inserted what we wanted.
                    args.setText(null);
                }
            }
        
            public void imageFieldMerging(ImageFieldMergingArgs args)
            {
                // Do nothing.
            }
        }
      • hasMacros

        public boolean hasMacros()
        
        Returns true if the document has a VBA project (macros).
        See Also:
        removeMacros()
      • hasRevisions

        public boolean hasRevisions()
        
        Returns true if the document has any tracked changes. This property is a shortcut for comparing RevisionCollection.Count to zero.
      • getHyphenationOptions

        public HyphenationOptions getHyphenationOptions()
        
        Provides access to document hyphenation options.

        Example:

        Shows how to configure document hyphenation options.
        Document doc = new Document();
        // Create new Run with text that we want to move to the next line using the hyphen
        Run run = new Run(doc);
        {
            run.setText("poqwjopiqewhpefobiewfbiowefob ewpj weiweohiewobew ipo efoiewfihpewfpojpief pijewfoihewfihoewfphiewfpioihewfoihweoihewfpj");
        }
        
        Paragraph para = doc.getFirstSection().getBody().getParagraphs().get(0);
        para.appendChild(run);
        
        doc.getHyphenationOptions().setAutoHyphenation(true);
        doc.getHyphenationOptions().setConsecutiveHyphenLimit(2);
        doc.getHyphenationOptions().setHyphenationZone(720); // 0.5 inch
        doc.getHyphenationOptions().setHyphenateCaps(true);
        
        doc.save(getMyDir() + "\\Artifacts\\HyphenationOptions.docx");
      • isComposite

        public boolean isComposite()
        
        Returns true as this node can have child nodes.

        Example:

        Shows how to efficiently visit all direct and indirect children of a composite node.
        public void recurseAllNodes() throws Exception
        {
            // Open a document.
            Document doc = new Document(getMyDir() + "Node.RecurseAllNodes.doc");
        
            // Invoke the recursive function that will walk the tree.
            traverseAllNodes(doc);
        }
        
        /**
         * A simple function that will walk through all children of a specified node recursively
         * and print the type of each node to the screen.
         */
        public void traverseAllNodes(CompositeNode parentNode)
        {
            // This is the most efficient way to loop through immediate children of a node.
            for (Node childNode = parentNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling())
            {
                // Do some useful work.
                System.out.println(Node.nodeTypeToString(childNode.getNodeType()));
        
                // Recurse into the node if it is a composite node.
                if (childNode.isComposite()) traverseAllNodes((CompositeNode) childNode);
            }
        }
      • getLastChild

        public Node getLastChild()
        
        Gets the last child of the node. If there is no last child node, a null is returned.

        Example:

        Demonstrates use of methods of Node and CompositeNode to remove a section before the last section in the document.
        // Document is a CompositeNode and LastChild returns the last child node in the Document node.
        // Since the Document can contain only Section nodes, the last child is the last section.
        Node lastSection = doc.getLastChild();
        
        // Each node knows its next and previous sibling nodes.
        // Previous sibling of a section is a section before the specified section.
        // If the node is the first child, PreviousSibling will return null.
        Node sectionBeforeLast = lastSection.getPreviousSibling();
        
        if (sectionBeforeLast != null) doc.removeChild(sectionBeforeLast);
      • getLastSection

        public Section getLastSection()
        
        Gets the last section in the document. Returns null if there are no sections.
      • getLayoutOptions

        public LayoutOptions getLayoutOptions()
        
        Gets a LayoutOptions object that represents options to control the layout process of this document.
      • getLists

        public ListCollection getLists()
        
        Provides access to the list formatting used in the document.

        For more information see the description of the ListCollection class.

        Example:

        Shows how to specify list level number when building a list using DocumentBuilder.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Create a numbered list based on one of the Microsoft Word list templates and
        // apply it to the current paragraph in the document builder.
        builder.getListFormat().setList(doc.getLists().add(ListTemplate.NUMBER_ARABIC_DOT));
        
        // There are 9 levels in this list, lets try them all.
        for (int i = 0; i < 9; i++)
        {
            builder.getListFormat().setListLevelNumber(i);
            builder.writeln("Level " + i);
        }
        
        // Create a bulleted list based on one of the Microsoft Word list templates
        // and apply it to the current paragraph in the document builder.
        builder.getListFormat().setList(doc.getLists().add(ListTemplate.BULLET_DIAMONDS));
        
        // There are 9 levels in this list, lets try them all.
        for (int i = 0; i < 9; i++)
        {
            builder.getListFormat().setListLevelNumber(i);
            builder.writeln("Level " + i);
        }
        
        // This is a way to stop list formatting.
        builder.getListFormat().setList(null);
        
        builder.getDocument().save(getMyDir() + "\\Artifacts\\Lists.SpecifyListLevel.doc");
        See Also:
        ListCollection, List, ListFormat
      • getMailMerge

        public MailMerge getMailMerge()
        
        Returns a MailMerge object that represents the mail merge functionality for the document.

        Example:

        Executes mail merge from data stored in a ResultSet.
        Document doc = new Document(getMyDir() + "MailMerge.ExecuteDataTable.doc");
        
        // This example creates a table, but you would normally load table from a database. 
        DataTable table = new DataTable("Test");
        table.getColumns().add("CustomerName");
        table.getColumns().add("Address");
        table.getRows().add(new Object[] { "Thomas Hardy", "120 Hanover Sq., London" });
        table.getRows().add(new Object[] { "Paolo Accorti", "Via Monte Bianco 34, Torino" });
        
        // Field values from the table are inserted into the mail merge fields found in the document.
        doc.getMailMerge().execute(table);
        
        doc.save(getMyDir() + "\\Artifacts\\MailMerge.ExecuteDataTable.doc");

        Example:

        Executes a mail merge with repeatable regions.
        public void executeWithRegionsDataTable() throws Exception
        {
            Document doc = new Document(getMyDir() + "MailMerge.ExecuteWithRegions.doc");
        
            int orderId = 10444;
        
            // Perform several mail merge operations populating only part of the document each time.
        
            // Use DataTable as a data source.
            // The table name property should be set to match the name of the region defined in the document.
            DataTable orderTable = getTestOrder(orderId);
            doc.getMailMerge().executeWithRegions(orderTable);
        
            DataTable orderDetailsTable = getTestOrderDetails(orderId, "ExtendedPrice DESC");
            doc.getMailMerge().executeWithRegions(orderDetailsTable);
        
            doc.save(getMyDir() + "\\Artifacts\\MailMerge.ExecuteWithRegionsDataTable.doc");
        }
        
        private static DataTable getTestOrder(int orderId) throws Exception
        {
            java.sql.ResultSet resultSet = executeDataTable(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", Integer.toString(orderId)));
        
            return new DataTable(resultSet, "Orders");
        }
        
        private static DataTable getTestOrderDetails(int orderId, String orderBy) throws Exception
        {
            StringBuilder builder = new StringBuilder();
        
            builder.append(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0}", Integer.toString(orderId)));
        
            if ((orderBy != null) && (orderBy.length() > 0))
            {
                builder.append(" ORDER BY ");
                builder.append(orderBy);
            }
        
            java.sql.ResultSet resultSet = executeDataTable(builder.toString());
            return new DataTable(resultSet, "OrderDetails");
        }
        
        /**
         * Utility function that creates a connection, command,
         * executes the command and return the result in a DataTable.
         */
        private static java.sql.ResultSet executeDataTable(String commandText) throws Exception
        {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");// Loads the driver
        
            // Open the database connection.
            String connString = "jdbc:ucanaccess://" + getDatabaseDir() + "Northwind.mdb";
        
            // From Wikipedia: The Sun driver has a known issue with character encoding and Microsoft Access databases.
            // Microsoft Access may use an encoding that is not correctly translated by the driver, leading to the replacement
            // in strings of, for example, accented characters by question marks.
            //
            // In this case I have to set CP1252 for the european characters to come through in the data values.
            java.util.Properties props = new java.util.Properties();
            props.put("charSet", "Cp1252");
            props.put("UID", "Admin");
        
            // DSN-less DB connection.
            java.sql.Connection conn = java.sql.DriverManager.getConnection(connString, props);
        
            // Create and execute a command.
            java.sql.Statement statement = conn.createStatement();
            return statement.executeQuery(commandText);
        }
      • getMailMergeSettings/setMailMergeSettings

        public MailMergeSettings getMailMergeSettings() / public void setMailMergeSettings(MailMergeSettings value)
        
        Gets or sets the object that contains all of the mail merge information for a document.

        You can use this object to specify a mail merge data source for a document and this information (along with the available data fields) will appear in Microsoft Word when the user opens this document. Or you can use this object to query mail merge settings that the user has specified in Microsoft Word for this document.

        This object is never null.

      • getNextSibling

        public Node getNextSibling()
        
        Gets the node immediately following this node. If there is no next node, a null is returned.

        Example:

        Shows how to enumerate immediate child nodes of a composite node using NextSibling. In this example we enumerate all paragraphs of a section body.
        // Get the section that we want to work on.
        Section section = doc.getSections().get(0);
        Body body = section.getBody();
        
        // Loop starting from the first child until we reach null.
        for (Node node = body.getFirstChild(); node != null; node = node.getNextSibling())
        {
            // Output the types of the nodes that we come across.
            System.out.println(Node.nodeTypeToString(node.getNodeType()));
        }

        Example:

        Shows how to efficiently visit all direct and indirect children of a composite node.
        public void recurseAllNodes() throws Exception
        {
            // Open a document.
            Document doc = new Document(getMyDir() + "Node.RecurseAllNodes.doc");
        
            // Invoke the recursive function that will walk the tree.
            traverseAllNodes(doc);
        }
        
        /**
         * A simple function that will walk through all children of a specified node recursively
         * and print the type of each node to the screen.
         */
        public void traverseAllNodes(CompositeNode parentNode)
        {
            // This is the most efficient way to loop through immediate children of a node.
            for (Node childNode = parentNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling())
            {
                // Do some useful work.
                System.out.println(Node.nodeTypeToString(childNode.getNodeType()));
        
                // Recurse into the node if it is a composite node.
                if (childNode.isComposite()) traverseAllNodes((CompositeNode) childNode);
            }
        }
      • getNodeChangingCallback/setNodeChangingCallback

        public INodeChangingCallback getNodeChangingCallback() / public void setNodeChangingCallback(INodeChangingCallback value)
        
        Called when a node is inserted or removed in the document.

        Example:

        Shows how to implement custom logic over node insertion in the document by changing the font of inserted HTML content.
        public void testNodeChangingInDocument() throws Exception
        {
            // Create a blank document object
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            // Set up and pass the object which implements the handler methods.
            doc.setNodeChangingCallback(new HandleNodeChanging_FontChanger());
        
            // Insert sample HTML content
            builder.insertHtml("<p>Hello World</p>");
        
            doc.save(getMyDir() + "\\Artifacts\\Document.FontChanger.doc");
        
            // Check that the inserted content has the correct formatting
            Run run = (Run) doc.getChild(NodeType.RUN, 0, true);
            Assert.assertEquals(run.getFont().getSize(), 24.0);
            Assert.assertEquals(run.getFont().getName(), "Arial");
        }
        
        public class HandleNodeChanging_FontChanger implements INodeChangingCallback
        {
            // Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document
            public void nodeInserted(NodeChangingArgs args)
            {
                // Change the font of inserted text contained in the Run nodes.
                if (args.getNode().getNodeType() == NodeType.RUN)
                {
                    Font font = ((Run) args.getNode()).getFont();
                    font.setSize(24);
                    font.setName("Arial");
                }
            }
        
            public void nodeInserting(NodeChangingArgs args)
            {
                // Do Nothing
            }
        
            public void nodeRemoved(NodeChangingArgs args)
            {
                // Do Nothing
            }
        
            public void nodeRemoving(NodeChangingArgs args)
            {
                // Do Nothing
            }
        }
      • getNodeType

        public int getNodeType()
        
        Returns NodeType.Document. The value of the property is NodeType integer constant.

        Example:

        Shows how to retrieve the NodeType enumeration of nodes.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // Let's pick a node that we can't be quite sure of what type it is.
        // In this case lets pick the first node of the first paragraph in the body of the document
        Node node = doc.getFirstSection().getBody().getFirstParagraph().getFirstChild();
        System.out.println("NodeType of first child: " + Node.nodeTypeToString(node.getNodeType()));
        
        // This time let's pick a node that we know the type of. Create a new paragraph and a table node.
        Paragraph para = new Paragraph(doc);
        Table table = new Table(doc);
        
        // Access to NodeType for typed nodes will always return their specific NodeType.
        // i.e A paragraph node will always return NodeType.Paragraph, a table node will always return NodeType.Table.
        System.out.println("NodeType of Paragraph: " + Node.nodeTypeToString(para.getNodeType()));
        System.out.println("NodeType of Table: " + Node.nodeTypeToString(table.getNodeType()));
      • getOriginalFileName

        public java.lang.String getOriginalFileName()
        
        Gets the original file name of the document.

        Returns null if the document was loaded from a stream or created blank.

        Example:

        Shows how to retrieve the details of the path, filename and LoadFormat of a document from when the document was first loaded into memory.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // This property will return the full path and file name where the document was loaded from.
        String originalFilePath = doc.getOriginalFileName();
        // Let's get just the file name from the full path.
        String originalFileName = new File(originalFilePath).getName();
        
        // This is the original LoadFormat of the document.
        int loadFormat = doc.getOriginalLoadFormat();

        Example:

        Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.
        // Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format. 
        // These are both times where you might need extract the file format as it's not visible
        FileInputStream docStream = new FileInputStream(getMyDir() + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
        FileFormatInfo info = FileFormatUtil.detectFileFormat(docStream);
        
        // Retrieve the LoadFormat of the document.
        int loadFormat = info.getLoadFormat();
        
        // Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations.
        //
        // Method #1
        // Convert the LoadFormat to a string first for working with. The string will include the leading dot infront of the extension.
        String fileExtension = FileFormatUtil.loadFormatToExtension(loadFormat);
        // Now convert this extension into the corresponding SaveFormat enumeration
        int saveFormat = FileFormatUtil.extensionToSaveFormat(fileExtension);
        
        // Method #2
        // Convert the LoadFormat enumeration directly to the SaveFormat enumeration.
        saveFormat = FileFormatUtil.loadFormatToSaveFormat(loadFormat);
        
        
        // Load a document from the stream.
        // Note that in Java we cannot reuse the same InputStream instance that was used for file format detection because InputStream is not seekable.
        docStream = new FileInputStream(getMyDir() + "Document.FileWithoutExtension"); // The file format of this document is actually ".doc"
        Document doc = new Document(docStream);
        
        // Save the document with the original file name, " Out" and the document's file extension.
        doc.save(getMyDir() + "\\Artifacts\\Document.WithFileExtension" + FileFormatUtil.saveFormatToExtension(saveFormat));
      • getOriginalLoadFormat

        public int getOriginalLoadFormat()
        
        Gets the format of the original document that was loaded into this object. The value of the property is LoadFormat integer constant.

        If you created a new blank document, returns the LoadFormat.DOC value.

        Example:

        Shows how to retrieve the details of the path, filename and LoadFormat of a document from when the document was first loaded into memory.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // This property will return the full path and file name where the document was loaded from.
        String originalFilePath = doc.getOriginalFileName();
        // Let's get just the file name from the full path.
        String originalFileName = new File(originalFilePath).getName();
        
        // This is the original LoadFormat of the document.
        int loadFormat = doc.getOriginalLoadFormat();
      • getPackageCustomParts/setPackageCustomParts

        public CustomPartCollection getPackageCustomParts() / public void setPackageCustomParts(CustomPartCollection value)
        
        Gets or sets the collection of custom parts (arbitrary content) that are linked to the OOXML package using "unknown relationships".

        Do not confuse these custom parts with Custom XML Data. If you need to access Custom XML parts, use the CustomXmlParts property.

        This collection contains OOXML parts whose parent is the OOXML package and they targets are of an "unknown relationship". For more information see CustomPart.

        Aspose.Words loads and saves custom parts into OOXML documents only.

        This property cannot be null.

        See Also:
        CustomPart
      • getPageColor/setPageColor

        public java.awt.Color getPageColor() / public void setPageColor(java.awt.Color value)
        
        Gets or sets the page color of the document. This property is a simpler version of BackgroundShape.

        This property provides a simple way to specify a solid page color for the document. Setting this property creates and sets an appropriate BackgroundShape.

        If the page color is not set (e.g. there is no background shape in the document) returns a zero color.

        See Also:
        BackgroundShape
      • getPageCount

        public int getPageCount()
        
        Gets the number of pages in the document as calculated by the most recent page layout operation.

        Example:

        Shows how to invoke page layout and retrieve the number of pages in the document.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // This invokes page layout which builds the document in memory so note that with large documents this
        // method can take time. After invoking this method, any rendering operation e.g rendering to PDF or image
        // will be instantaneous.
        int pageCount = doc.getPageCount();
        See Also:
        updatePageLayout()
      • getParentNode

        public CompositeNode getParentNode()
        
        Gets the immediate parent of this node.

        If a node has just been created and not yet added to the tree, or if it has been removed from the tree, the parent is null.

        Example:

        Shows how to access the parent node.
        // Create a new empty document. It has one section.
        Document doc = new Document();
        
        // The section is the first child node of the document.
        Node section = doc.getFirstChild();
        
        // The section's parent node is the document.
        System.out.println("Section parent is the document: " + (doc == section.getParentNode()));

        Example:

        Shows that when you create any node, it requires a document that will own the node.
        // Open a file from disk.
        Document doc = new Document();
        
        // Creating a new node of any type requires a document passed into the constructor.
        Paragraph para = new Paragraph(doc);
        
        // The new paragraph node does not yet have a parent.
        System.out.println("Paragraph has no parent node: " + (para.getParentNode() == null));
        
        // But the paragraph node knows its document.
        System.out.println("Both nodes' documents are the same: " + (para.getDocument() == doc));
        
        // The fact that a node always belongs to a document allows us to access and modify
        // properties that reference the document-wide data such as styles or lists.
        para.getParagraphFormat().setStyleName("Heading 1");
        
        // Now add the paragraph to the main text of the first section.
        doc.getFirstSection().getBody().appendChild(para);
        
        // The paragraph node is now a child of the Body node.
        System.out.println("Paragraph has a parent node: " + (para.getParentNode() != null));
      • getPreviousSibling

        public Node getPreviousSibling()
        
        Gets the node immediately preceding this node. If there is no preceding node, a null is returned.

        Example:

        Demonstrates use of methods of Node and CompositeNode to remove a section before the last section in the document.
        // Document is a CompositeNode and LastChild returns the last child node in the Document node.
        // Since the Document can contain only Section nodes, the last child is the last section.
        Node lastSection = doc.getLastChild();
        
        // Each node knows its next and previous sibling nodes.
        // Previous sibling of a section is a section before the specified section.
        // If the node is the first child, PreviousSibling will return null.
        Node sectionBeforeLast = lastSection.getPreviousSibling();
        
        if (sectionBeforeLast != null) doc.removeChild(sectionBeforeLast);
      • getProtectionType

        public int getProtectionType()
        
        Gets the currently active document protection type. The value of the property is ProtectionType integer constant.

        This property allows to retrieve the currently set document protection type. To change the document protection type use the protect(int,java.lang.String) and unprotect() methods.

        When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

        Note that document protection is different from write protection. Write protection is specified using the WriteProtection

        Example:

        Shows how to get protection type currently set in the document.
        Document doc = new Document(getMyDir() + "Document.doc");
        int protectionType = doc.getProtectionType();
        See Also:
        protect(int,java.lang.String), unprotect(), WriteProtection
      • getRange

        public Range getRange()
        
        Returns a Range object that represents the portion of a document that is contained in this node.

        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());
      • getRemovePersonalInformation/setRemovePersonalInformation

        public boolean getRemovePersonalInformation() / public void setRemovePersonalInformation(boolean value)
        
        Gets or sets a flag indicating that Microsoft Word will remove all user information from comments, revisions and document properties upon saving the document.
      • getResourceLoadingCallback/setResourceLoadingCallback

        public IResourceLoadingCallback getResourceLoadingCallback() / public void setResourceLoadingCallback(IResourceLoadingCallback value)
        
        Allows to control how external resources are loaded.
      • getRevisions

        public RevisionCollection getRevisions()
        
        Gets a collection of revisions (tracked changes) that exist in this document.

        The returned collection is a "live" collection, which means if you remove parts of a document that contain revisions, the deleted revisions will automatically disappear from this collection.

      • getSections

        public SectionCollection getSections()
        
        Returns a collection that represents all sections in the document.

        Example:

        Specifies how the section starts, from a new page, on the same page or other.
        Document doc = new Document();
        doc.getSections().get(0).getPageSetup().setSectionStart(com.aspose.words.SectionStart.CONTINUOUS);

        Example:

        Shows how to add/remove sections in a document.
        // Open the document.
        Document doc = new Document(getMyDir() + "Section.AddRemove.doc");
        
        // This shows what is in the document originally. The document has two sections.
        System.out.println(doc.getText());
        
        // Delete the first section from the document
        doc.getSections().removeAt(0);
        
        // Duplicate the last section and append the copy to the end of the document.
        int lastSectionIdx = doc.getSections().getCount() - 1;
        Section newSection = doc.getSections().get(lastSectionIdx).deepClone();
        doc.getSections().add(newSection);
        
        // Check what the document contains after we changed it.
        System.out.println(doc.getText());
      • getShadeFormData/setShadeFormData

        public boolean getShadeFormData() / public void setShadeFormData(boolean value)
        
        Specifies whether to turn on the gray shading on form fields.
      • getStyles

        public StyleCollection getStyles()
        
        Returns a collection of styles defined in the document.

        For more information see the description of the StyleCollection class.

        Example:

        Shows how to get access to the collection of styles defined in the document.
        Document doc = new Document();
        StyleCollection styles = doc.getStyles();
        
        for (Style style : styles)
            System.out.println(style.getName());

        Example:

        Shows how to create and use a paragraph style with list formatting.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Create a paragraph style and specify some formatting for it.
        Style style = doc.getStyles().add(StyleType.PARAGRAPH, "MyStyle1");
        style.getFont().setSize(24);
        style.getFont().setName("Verdana");
        style.getParagraphFormat().setSpaceAfter(12);
        
        // Create a list and make sure the paragraphs that use this style will use this list.
        style.getListFormat().setList(doc.getLists().add(ListTemplate.BULLET_DEFAULT));
        style.getListFormat().setListLevelNumber(0);
        
        // Apply the paragraph style to the current paragraph in the document and add some text.
        builder.getParagraphFormat().setStyle(style);
        builder.writeln("Hello World: MyStyle1, bulleted.");
        
        // Change to a paragraph style that has no list formatting.
        builder.getParagraphFormat().setStyle(doc.getStyles().get("Normal"));
        builder.writeln("Hello World: Normal.");
        
        builder.getDocument().save(getMyDir() + "\\Artifacts\\Lists.ParagraphStyleBulleted.doc");
        See Also:
        StyleCollection, Style
      • getTheme

        public Theme getTheme()
        
        Gets the Theme object for this document.
      • getTrackRevisions/setTrackRevisions

        public boolean getTrackRevisions() / public void setTrackRevisions(boolean value)
        
        True if changes are tracked when this document is edited in Microsoft Word.

        Setting this option only instructs Microsoft Word whether the track changes is turned on or off. This property has no effect on changes to the document that you make programmatically via Aspose.Words.

        If you want to automatically track changes as they are made programmatically by Aspose.Words to this document use the startTrackRevisions(java.lang.String,java.util.Date) method.

      • getVariables

        public VariableCollection getVariables()
        
        Returns the collection of variables added to a document or template.

        Example:

        Shows how to enumerate over document variables.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        for (java.util.Map.Entry entry : doc.getVariables())
        {
            String name = entry.getKey().toString();
            String value = entry.getValue().toString();
        
            // Do something useful.
            System.out.println(MessageFormat.format("Name: {0}, Value: {1}", name, value));
        }
      • getVersionsCount

        public int getVersionsCount()
        
        Gets the number of document versions that was stored in the DOC document.

        Versions in Microsoft Word are accessed via the File/Versions menu. Microsoft Word supports versions only for DOC files.

        This property allows to detect if there were document versions stored in this document before it was opened in Aspose.Words. Aspose.Words provides no other support for document versions. If you save this document using Aspose.Words, the document will be saved without versions.

      • getViewOptions

        public ViewOptions getViewOptions()
        
        Provides options to control how the document is displayed in Microsoft Word.

        Example:

        The following code shows how to make sure the document is displayed at 50% zoom when opened in Microsoft Word.
        Document doc = new Document(getMyDir() + "Document.doc");
        doc.getViewOptions().setViewType(ViewType.PAGE_LAYOUT);
        doc.getViewOptions().setZoomPercent(50);
        doc.save(getMyDir() + "\\Artifacts\\Document.SetZoom.doc");
      • getWarningCallback/setWarningCallback

        public IWarningCallback getWarningCallback() / public void setWarningCallback(IWarningCallback value)
        
        Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss. Document may generate warnings at any stage of its existence, so it's important to setup warning callback as early as possible to avoid the warnings loss. E.g. such properties as PageCount actually build the document layout which is used later for rendering, and the layout warnings may be lost if warning callback is specified just for the rendering calls later.

        Example:

        Shows how to implement the IWarningCallback to be notified of any font substitution during document save.
        public static class HandleDocumentWarnings implements IWarningCallback
        {
            /**
             *  Our callback only needs to implement the "Warning" method. This method is called whenever there is a
             *  potential issue during document processing. The callback can be set to listen for warnings generated during document
             *  load and/or document save.
             */
            public void warning(WarningInfo info)
            {
                // We are only interested in fonts being substituted.
                if (info.getWarningType() == WarningType.FONT_SUBSTITUTION)
                {
                    System.out.println("Font substitution: " + info.getDescription());
                }
            }
        
        }

        Example:

        Demonstrates how to receive notifications of font substitutions by using IWarningCallback.
        // Load the document to render.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // Create a new class implementing IWarningCallback and assign it to the PdfSaveOptions class.
        HandleDocumentWarnings callback = new HandleDocumentWarnings();
        doc.setWarningCallback(callback);
        
        // We can choose the default font to use in the case of any missing fonts.
        FontSettings.getDefaultInstance().setDefaultFontName("Arial");
        
        // For testing we will set Aspose.Words to look for fonts only in a folder which doesn't exist. Since Aspose.Words won't
        // find any fonts in the specified directory, then during rendering the fonts in the document will be substituted with the default 
        // font specified under FontSettings.DefaultFontName. We can pick up on this substitution using our callback.
        FontSettings.getDefaultInstance().setFontsFolder("", false);
        
        // Pass the save options along with the save path to the save method.
        doc.save(getMyDir() + "\\Artifacts\\Rendering.MissingFontNotification.pdf");
      • getWriteProtection

        public WriteProtection getWriteProtection()
        
        Provides access to the document write protection options.
    • Method Detail

      • accept

        public boolean accept(DocumentVisitor visitor)
                      throws java.lang.Exception
        Accepts a visitor.

        Enumerates over this node and all of its children. Each node calls a corresponding method on DocumentVisitor.

        For more info see the Visitor design pattern.

        Calls DocumentVisitor.VisitDocumentStart, then calls Accept for all child nodes of the document and calls DocumentVisitor.VisitDocumentEnd at the end.
        Parameters:
        visitor - The visitor that will visit the nodes.
        Returns:
        True if all nodes were visited; false if DocumentVisitor stopped the operation before visiting all nodes.

        Example:

        Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
        public void toText() throws Exception
        {
            // Open the document we want to convert.
            Document doc = new Document(getMyDir() + "DocumentVisitor.Destination.docx");
        
            // Create an object that inherits from the DocumentVisitor class.
            MyDocToTxtWriter myConverter = new MyDocToTxtWriter();
        
            // This is the well known Visitor pattern. Get the model to accept a visitor.
            // The model will iterate through itself by calling the corresponding methods
            // on the visitor object (this is called visiting).
            //
            // Note that every node in the object model has the Accept method so the visiting
            // can be executed not only for the whole document, but for any node in the document.
            doc.accept(myConverter);
        
            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor.
            System.out.println(myConverter.getText());
        }
        
        /**
         * Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
         */
        public class MyDocToTxtWriter extends DocumentVisitor
        {
            public MyDocToTxtWriter()
            {
                mIsSkipText = false;
                mBuilder = new StringBuilder();
            }
        
            /**
             * Gets the plain text of the document that was accumulated by the visitor.
             */
            public String getText()
            {
                return mBuilder.toString();
            }
        
            /**
             * Called when a Run node is encountered in the document.
             */
            public int visitRun(Run run) throws Exception
            {
                appendText(run.getText());
        
                // Let the visitor continue visiting other nodes.
                return VisitorAction.CONTINUE;
            }
        
            /**
             * Called when a FieldStart node is encountered in the document.
             */
            public int visitFieldStart(FieldStart fieldStart)
            {
                // In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
                // after a field start character. We want to skip field codes and output field
                // result only, therefore we use a flag to suspend the output while inside a field code.
                //
                // Note this is a very simplistic implementation and will not work very well
                // if you have nested fields in a document.
                mIsSkipText = true;
        
                return VisitorAction.CONTINUE;
            }
        
            /**
             * Called when a FieldSeparator node is encountered in the document.
             */
            public int visitFieldSeparator(FieldSeparator fieldSeparator)
            {
                // Once reached a field separator node, we enable the output because we are
                // now entering the field result nodes.
                mIsSkipText = false;
        
                return VisitorAction.CONTINUE;
            }
        
            /**
             * Called when a FieldEnd node is encountered in the document.
             */
            public int visitFieldEnd(FieldEnd fieldEnd)
            {
                // Make sure we enable the output when reached a field end because some fields
                // do not have field separator and do not have field result.
                mIsSkipText = false;
        
                return VisitorAction.CONTINUE;
            }
        
            /**
             * Called when visiting of a Paragraph node is ended in the document.
             */
            public int visitParagraphEnd(Paragraph paragraph) throws Exception
            {
                // When outputting to plain text we output Cr+Lf characters.
                appendText(ControlChar.CR_LF);
        
                return VisitorAction.CONTINUE;
            }
        
            public int visitBodyStart(Body body)
            {
                // We can detect beginning and end of all composite nodes such as Section, Body,
                // Table, Paragraph etc and provide custom handling for them.
                mBuilder.append("*** Body Started ***\r\n");
        
                return VisitorAction.CONTINUE;
            }
        
            public int visitBodyEnd(Body body)
            {
                mBuilder.append("*** Body Ended ***\r\n");
                return VisitorAction.CONTINUE;
            }
        
            /**
             * Called when a HeaderFooter node is encountered in the document.
             */
            public int visitHeaderFooterStart(HeaderFooter headerFooter)
            {
                // Returning this value from a visitor method causes visiting of this
                // node to stop and move on to visiting the next sibling node.
                // The net effect in this example is that the text of headers and footers
                // is not included in the resulting output.
                return VisitorAction.SKIP_THIS_NODE;
            }
        
            /**
             * Called when an AbsolutePositionTab is encountered in the document.
             */
            public int visitAbsolutePositionTab(AbsolutePositionTab tab)
            {
                mBuilder.append("\t");
                return VisitorAction.CONTINUE;
            }
        
            /**
             * Called when a BookmarkStart is encountered in the document.
             */
            public int visitBookmarkStart(BookmarkStart bookmarkStart)
            {
                mBuilder.append("[");
                return VisitorAction.CONTINUE;
            }
        
            /**
             * Called when a BookmarkEnd is encountered in the document.
             */
            public int visitBookmarkEnd(BookmarkEnd bookmarkEnd)
            {
                mBuilder.append("]");
                return VisitorAction.CONTINUE;
            }
        
            /**
             * Adds text to the current output. Honours the enabled/disabled output flag.
             */
            private void appendText(String text)
            {
                if (!mIsSkipText) mBuilder.append(text);
            }
        
            private final StringBuilder mBuilder;
            private boolean mIsSkipText;
        }
      • acceptAllRevisions

        public void acceptAllRevisions()
                               throws java.lang.Exception
        Accepts all tracked changes in the document. This method is a shortcut for RevisionCollection.acceptAll().

        Example:

        Shows how to accept all tracking changes in the document.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // Start tracking and make some revisions.
        doc.startTrackRevisions("Author");
        doc.getFirstSection().getBody().appendParagraph("Hello world!");
        
        // Revisions will now show up as normal text in the output document.
        doc.acceptAllRevisions();
        doc.save(getMyDir() + "\\Artifacts\\Document.AcceptedRevisions.doc");
      • appendChild

        public Node appendChild(Node newChild)
        Adds the specified node to the end of the list of child nodes for this node.

        If the newChild is already in the tree, it is first removed.

        If the node being inserted was created from another document, you should use importNode(com.aspose.words.Node,boolean,int) to import the node to the current document. The imported node can then be inserted into the current document.

        Parameters:
        newChild - The node to add.
        Returns:
        The node added.

        Example:

        Creates a simple document from scratch using the Aspose.Words object model.
        // Create an "empty" document. Note that like in Microsoft Word,
        // the empty document has one section, body and one paragraph in it.
        Document doc = new Document();
        
        // This truly makes the document empty. No sections (not possible in Microsoft Word).
        doc.removeAllChildren();
        
        // Create a new section node.
        // Note that the section has not yet been added to the document,
        // but we have to specify the parent document.
        Section section = new Section(doc);
        
        // Append the section to the document.
        doc.appendChild(section);
        
        // Lets set some properties for the section.
        section.getPageSetup().setSectionStart(SectionStart.NEW_PAGE);
        section.getPageSetup().setPaperSize(PaperSize.LETTER);
        
        // The section that we created is empty, lets populate it. The section needs at least the Body node.
        Body body = new Body(doc);
        section.appendChild(body);
        
        // The body needs to have at least one paragraph.
        // Note that the paragraph has not yet been added to the document,
        // but we have to specify the parent document.
        // The parent document is needed so the paragraph can correctly work
        // with styles and other document-wide information.
        Paragraph para = new Paragraph(doc);
        body.appendChild(para);
        
        // We can set some formatting for the paragraph
        para.getParagraphFormat().setStyleName("Heading 1");
        para.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        
        // So far we have one empty paragraph in the document.
        // The document is valid and can be saved, but lets add some text before saving.
        // Create a new run of text and add it to our paragraph.
        Run run = new Run(doc);
        run.setText("Hello World!");
        run.getFont().setColor(Color.RED);
        para.appendChild(run);
        
        // As a matter of interest, you can retrieve text of the whole document and
        // see that \x000c is automatically appended. \x000c is the end of section character.
        System.out.println(doc.getText());
        
        // Save the document.
        doc.save(getMyDir() + "\\Artifacts\\Section.CreateFromScratch.doc");
      • appendDocument

        public void appendDocument(Document srcDoc, int importFormatMode)
        Appends the specified document to the end of this document.
        Parameters:
        srcDoc - The document to append.
        importFormatMode - A ImportFormatMode value. Specifies how to merge style formatting that clashes.

        Example:

        Shows how to use the AppendDocument method to combine all the documents in a folder to the end of a template document.
        // Lets start with a simple template and append all the documents in a folder to this document.
        Document baseDoc = new Document();
        
        // Add some content to the template.
        DocumentBuilder builder = new DocumentBuilder(baseDoc);
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
        builder.writeln("Template Document");
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.NORMAL);
        builder.writeln("Some content here");
        
        // Gather the files which will be appended to our template document.
        // In this case we search only for files with the ".doc" extension.
        File srcDir = new File(getMyDir());
        FilenameFilter filter = new FilenameFilter()
        {
            @Override
            public boolean accept(File dir, String name)
            {
                return name.endsWith(".doc");
            }
        };
        File[] files = srcDir.listFiles(filter);
        
        // The list of files may come in any order, let's sort the files by name so the documents are enumerated alphabetically.
        Arrays.sort(files);
        
        // Iterate through every file in the directory and append each one to the end of the template document.
        for (File file : files)
        {
            String fileName = file.getCanonicalPath();
        
            // We have some encrypted test documents in our directory, Aspose.Words can open encrypted documents
            // but only with the correct password. Let's just skip them here for simplicity.
            FileFormatInfo info = FileFormatUtil.detectFileFormat(fileName);
            if (info.isEncrypted()) continue;
        
            Document subDoc = new Document(fileName);
            baseDoc.appendDocument(subDoc, ImportFormatMode.USE_DESTINATION_STYLES);
        }
        
        // Save the combined document to disk.
        baseDoc.save(path);

        Example:

        Shows how to append a document to the end of another document.
        // The document that the content will be appended to.
        Document dstDoc = new Document(getMyDir() + "Document.doc");
        // The document to append.
        Document srcDoc = new Document(getMyDir() + "DocumentBuilder.doc");
        
        // Append the source document to the destination document.
        // Pass format mode to retain the original formatting of the source document when importing it.
        dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
        
        // Save the document.
        dstDoc.save(getMyDir() + "\\Artifacts\\Document.AppendDocument.doc");
      • cleanup

        public void cleanup()
                    throws java.lang.Exception
        Cleans unused styles and lists from the document.
      • cleanup

        public void cleanup(CleanupOptions options)
                    throws java.lang.Exception
        Cleans unused styles and lists from the document depending on given CleanupOptions.

        Example:

        Shows how to remove all unused styles and lists from a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        CleanupOptions cleanupOptions = new CleanupOptions();
        cleanupOptions.setUnusedLists(true);
        cleanupOptions.setUnusedStyles(true);
        
        doc.cleanup(cleanupOptions);
      • compare

        public void compare(Document document, java.lang.String author, java.util.Date dateTime)
                    throws java.lang.Exception
        Compares this document with another document producing changes as number of edit and format revisions Revision. The following document nodes are not compared at the moment:
        Note: Documents must not have revisions before comparison.
        Parameters:
        document - Document to compare.
        author - Initials of the author to use for revisions.
        dateTime - The date and time to use for revisions.

        Example:

        Shows how to apply the compare method to two documents and then use the results.
        Document doc1 = new Document(getMyDir() + "Document.Compare.1.doc");
        Document doc2 = new Document(getMyDir() + "Document.Compare.2.doc");
        
        // If either document has a revision, an exception will be thrown.
        if (doc1.getRevisions().getCount() == 0 && doc2.getRevisions().getCount() == 0)
            doc1.compare(doc2, "authorName", new Date());
        
        // If doc1 and doc2 are different, doc1 now has some revisions after the comparison, which can now be viewed and processed.
        for (Revision r : doc1.getRevisions())
            System.out.println(r.getRevisionType());
        
        // All the revisions in doc1 are differences between doc1 and doc2, so accepting them on doc1 transforms doc1 into doc2.
        doc1.getRevisions().acceptAll();
        
        // doc1, when saved, now resembles doc2.
        doc1.save(getMyDir() + "\\Artifacts\\Document.Compare.doc");
      • compare

        public void compare(Document document, java.lang.String author, java.util.Date dateTime, CompareOptions options)
                    throws java.lang.Exception
        Compares this document with another document producing changes as a number of edit and format revisions Revision. Allows to specify comparison options using CompareOptions.
      • copyStylesFromTemplate

        public void copyStylesFromTemplate(Document template)
        Copies styles from the specified template to a document. When styles are copied from a template to a document, like-named styles in the document are redefined to match the style descriptions in the template. Unique styles from the template are copied to the document. Unique styles in the document remain intact.
      • copyStylesFromTemplate

        public void copyStylesFromTemplate(java.lang.String template)
                                   throws java.lang.Exception
        Copies styles from the specified template to a document. When styles are copied from a template to a document, like-named styles in the document are redefined to match the style descriptions in the template. Unique styles from the template are copied to the document. Unique styles in the document remain intact.
      • deepClone

        public Document deepClone()
        Performs a deep copy of the Document.
        Returns:
        The cloned document.

        Example:

        Shows how to deep clone a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        Document clone = doc.deepClone();
      • deepClone

        public Node deepClone(boolean isCloneChildren)

        Example:

        Shows how to clone composite nodes with and without their child nodes.
        // Create a new empty document.
        Document doc = new Document();
        
        // Add some text to the first paragraph
        Paragraph para = doc.getFirstSection().getBody().getFirstParagraph();
        para.appendChild(new Run(doc, "Some text"));
        
        // Clone the paragraph and the child nodes.
        Node cloneWithChildren = para.deepClone(true);
        // Only clone the paragraph and no child nodes.
        Node cloneWithoutChildren = para.deepClone(false);
      • ensureMinimum

        public void ensureMinimum()
        If the document contains no sections, creates one section with one paragraph.

        Example:

        Shows how to ensure the Document is valid (has the minimum nodes required to be valid).
        // Create a blank document then remove all nodes from it, the result will be a completely empty document.
        Document doc = new Document();
        doc.removeAllChildren();
        
        // Ensure that the document is valid. Since the document has no nodes this method will create an empty section
        // and add an empty paragraph to make it valid.
        doc.ensureMinimum();
      • expandTableStylesToDirectFormatting

        public void expandTableStylesToDirectFormatting()
                                                throws java.lang.Exception
        Converts formatting specified in table styles into direct formatting on tables in the document.

        This method exists because this version of Aspose.Words provides only limited support for table styles (see below). This method might be useful when you load a DOCX or WordprocessingML document that contains tables formatted with table styles and you need to query formatting of tables, cells, paragraphs or text.

        This version of Aspose.Words provides limited support for table styles as follows:

        • Table styles defined in DOCX or WordprocessingML documents are preserved as table styles when saving the document as DOCX or WordprocessingML.
        • Table styles defined in DOCX or WordprocessingML documents are automatically converted to direct formatting on tables when saving the document into any other format, rendering or printing.
        • Table styles defined in DOC documents are preserved as table styles when saving the document as DOC only.

        Example:

        Shows how to expand the formatting from styles onto the rows and cells of the table as direct formatting.
        Document doc = new Document(getMyDir() + "Table.TableStyle.docx");
        
        // Get the first cell of the first table in the document.
        Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
        Cell firstCell = table.getFirstRow().getFirstCell();
        
        // First print the color of the cell shading. This should be empty as the current shading
        // is stored in the table style.
        double cellShadingBefore = table.getFirstRow().getRowFormat().getHeight();
        System.out.println("Cell shading before style expansion: " + cellShadingBefore);
        
        // Expand table style formatting to direct formatting.
        doc.expandTableStylesToDirectFormatting();
        
        // Now print the cell shading after expanding table styles. A blue background pattern color
        // should have been applied from the table style.
        double cellShadingAfter = table.getFirstRow().getRowFormat().getHeight();
        System.out.println("Cell shading after style expansion: " + cellShadingAfter);
      • getAncestor

        public CompositeNode getAncestor(int ancestorType)
        Gets the first ancestor of the specified NodeType.
        Parameters:
        ancestorType - A NodeType value. The node type of the ancestor to retrieve.
        Returns:
        The ancestor of the specified type or null if no ancestor of this type was found.

        Example:

        Shows how to find out if a table contains another table or if the table itself is nested inside another table.
        public void calculateDepthOfNestedTables() throws Exception
        {
            Document doc = new Document(getMyDir() + "Table.NestedTables.doc");
            int tableIndex = 0;
        
            for (Table table : (Iterable<Table>) doc.getChildNodes(NodeType.TABLE, true))
            {
                // First lets find if any cells in the table have tables themselves as children.
                int count = getChildTableCount(table);
                System.out.println(MessageFormat.format("Table #{0} has {1} tables directly within its cells", tableIndex, count));
        
                // Now let's try the other way around, lets try find if the table is nested inside another table and at what depth.
                int tableDepth = getNestedDepthOfTable(table);
        
                if (tableDepth > 0)
                    System.out.println(MessageFormat.format("Table #{0} is nested inside another table at depth of {1}", tableIndex, tableDepth));
                else
                    System.out.println(MessageFormat.format("Table #{0} is a non nested table (is not a child of another table)", tableIndex));
        
                tableIndex++;
            }
        }
        
        /**
         * Calculates what level a table is nested inside other tables.
         *
         * @returns An integer containing the level the table is nested at.
         * 0 = Table is not nested inside any other table
         * 1 = Table is nested within one parent table
         * 2 = Table is nested within two parent tables etc..
         */
        private static int getNestedDepthOfTable(Table table)
        {
            int depth = 0;
        
            int type = table.getNodeType();
            // The parent of the table will be a Cell, instead attempt to find a grandparent that is of type Table
            Node parent = table.getAncestor(type);
        
            while (parent != null)
            {
                // Every time we find a table a level up we increase the depth counter and then try to find an
                // ancestor of type table from the parent.
                depth++;
                parent = parent.getAncestor(type);
            }
        
            return depth;
        }
        
        /**
         * Determines if a table contains any immediate child table within its cells.
         * Does not recursively traverse through those tables to check for further tables.
         *
         * @returns Returns true if at least one child cell contains a table.
         * Returns false if no cells in the table contains a table.
         */
        private static int getChildTableCount(Table table)
        {
            int tableCount = 0;
            // Iterate through all child rows in the table
            for (Row row : table.getRows())
            {
                // Iterate through all child cells in the row
                for (Cell Cell : row.getCells())
                {
                    // Retrieve the collection of child tables of this cell
                    TableCollection childTables = Cell.getTables();
        
                    // If this cell has a table as a child then return true
                    if (childTables.getCount() > 0) tableCount++;
                }
            }
        
            // No cell contains a table
            return tableCount;
        }
      • getAncestor

        public CompositeNode getAncestor(java.lang.Class ancestorType)
        Gets the first ancestor of the specified object type.

        The ancestor type matches if it is equal to ancestorType or derived from ancestorType.

        Parameters:
        ancestorType - The object type of the ancestor to retrieve.
        Returns:
        The ancestor of the specified type or null if no ancestor of this type was found.
      • getChild

        public Node getChild(int nodeType, int index, boolean isDeep)
        Returns an Nth child node that matches the specified type.

        If index is out of range, a null is returned.

        Note that markup nodes (NodeType.STRUCTURED_DOCUMENT_TAG and NodeType.SMART_TAG) are traversed even when isDeep = false and GetChild is invoked for non-markup node type. For example if the first run in a para is wrapped in a StructuredDocumentTag, it will still be returned by GetChild(NodeType.Run, 0, false).
        Parameters:
        nodeType - A NodeType value. Specifies the type of the child node.
        index - Zero based index of the child node to select. Negative indexes are also allowed and indicate access from the end, that is -1 means the last node.
        isDeep - True to select from all child nodes recursively. False to select only among immediate children. See remarks for more info.
        Returns:
        The child node that matches the criteria or null if no matching node is found.

        Example:

        Shows how to test if a node is inside a field by using an XPath expression.
        // Let's pick a document we know has some fields in.
        Document doc = new Document(getMyDir() + "MailMerge.MergeImage.doc");
        
        // Let's say we want to check if the Run below is inside a field.
        Run run = (Run) doc.getChild(NodeType.RUN, 5, true);
        
        // Evaluate the XPath expression. The resulting NodeList will contain all nodes found inside a field a field (between FieldStart
        // and FieldEnd exclusive). There can however be FieldStart and FieldEnd nodes in the list if there are nested fields
        // in the path. Currently does not find rare fields in which the FieldCode or FieldResult spans across multiple paragraphs.
        NodeList resultList = doc.selectNodes("//FieldStart/following-sibling::node()[following-sibling::FieldEnd]");
        
        // Check if the specified run is one of the nodes that are inside the field.
        for (Node node : (Iterable<Node>) resultList)
        {
            if (node == run)
            {
                System.out.println("The node is found inside a field");
                break;
            }
        }

        Example:

        Shows how to extract a specific child node from a CompositeNode by using the GetChild method and passing the NodeType and index.
        Paragraph paragraph = (Paragraph) doc.getChild(NodeType.PARAGRAPH, 0, true);
      • getChildNodes

        public NodeCollection getChildNodes(int nodeType, boolean isDeep)
        Returns a live collection of child nodes that match the specified type.

        The collection of nodes returned by this method is always live.

        A live collection is always in sync with the document. For example, if you selected all sections in a document and enumerate through the collection deleting the sections, the section is removed from the collection immediately when it is removed from the document.

        Parameters:
        nodeType - A NodeType value. Specifies the type of nodes to select.
        isDeep - True to select from all child nodes recursively. False to select only among immediate children.
        Returns:
        A live collection of child nodes of the specified type.

        Example:

        Shows how to extract images from a document and save them as files.
        public void extractImagesToFiles() throws Exception
        {
            Document doc = new Document(getMyDir() + "Image.SampleImages.doc");
        
            NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true);
            int imageIndex = 0;
            for (Shape shape : (Iterable<Shape>) shapes)
            {
                if (shape.hasImage())
                {
                    String imageFileName = java.text.MessageFormat.format("\\Artifacts\\Image.ExportImages.{0} Out{1}", imageIndex, FileFormatUtil.imageTypeToExtension(shape.getImageData().getImageType()));
                    shape.getImageData().save(getMyDir() + imageFileName);
                    imageIndex++;
                }
            }
        }

        Example:

        Demonstrates how to remove a specified TOC from a document.
        public void removeTOCFromDocument() throws Exception
        {
            // Open a document which contains a TOC.
            Document doc = new Document(getMyDir() + "Document.TableOfContents.doc");
        
            // Remove the first TOC from the document.
            Field tocField = doc.getRange().getFields().get(0);
            tocField.remove();
        
            // Save the output.
            doc.save(getMyDir() + "\\Artifacts\\Document.TableOfContentsRemoveTOC.doc");
        }
      • getPageInfo

        public PageInfo getPageInfo(int pageIndex)
                            throws java.lang.Exception
        Gets the page size, orientation and other information about a page that might be useful for printing or rendering.
        Parameters:
        pageIndex - The 0-based page index.

        Example:

        Renders a page of a Word document into a BufferedImage using a specified zoom factor.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        PageInfo pageInfo = doc.getPageInfo(0);
        
        // Let's say we want the image at 50% zoom.
        final float MY_SCALE = 0.50f;
        
        // Let's say we want the image at this resolution.
        final float MY_RESOLUTION = 200.0f;
        
        Dimension pageSize = pageInfo.getSizeInPixels(MY_SCALE, MY_RESOLUTION);
        
        BufferedImage img = new BufferedImage((int) pageSize.getWidth(), (int) pageSize.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D gr = img.createGraphics();
        
        try
        {
            // You can apply various settings to the Graphics object.
            gr.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        
            // Fill the page background.
            gr.setPaint(Color.black);
        
            // Render the page using the zoom.
            doc.renderToScale(0, gr, 0, 0, MY_SCALE);
        } finally
        {
            if (gr != null) gr.dispose();
        }
        
        ImageIO.write(img, "PNG", new File(getMyDir() + "\\Artifacts\\Rendering.RenderToScale.png"));
      • getText

        public java.lang.String getText()
        Gets the text of this node and of all its children.

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

        Example:

        Shows the difference between calling the GetText and ToString methods on a node.
        Document doc = new Document();
        
        // Enter a dummy field into the document.
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.insertField("MERGEFIELD Field");
        
        // GetText will retrieve all field codes and special characters
        System.out.println("GetText() Result: " + doc.getText());
        
        // ToString will export the node to the specified format. When converted to text it will not retrieve fields code
        // or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
        // This is the same as "viewing" the document as if it was opened in a text editor.
        System.out.println("ToString() Result: " + doc.toString(SaveFormat.TEXT));

        Example:

        Finds and outputs all paragraphs in a document that are bulleted or numbered.
        NodeCollection paras = doc.getChildNodes(NodeType.PARAGRAPH, true);
        for (Paragraph para : (Iterable<Paragraph>) paras)
        {
            if (para.getListFormat().isListItem())
            {
                System.out.println(java.text.MessageFormat.format("*** A paragraph belongs to list {0}", para.getListFormat().getList().getListId()));
                System.out.println(para.getText());
            }
        }
      • importNode

        public Node importNode(Node srcNode, boolean isImportChildren)

        Imports a node from another document to the current document.

        This method uses the ImportFormatMode.USE_DESTINATION_STYLES option to resolve formatting.

        Importing a node creates a copy of the source node belonging to the importing document. The returned node has no parent. The source node is not altered or removed from the original document.

        Before a node from another document can be inserted into this document, it must be imported. During import, document-specific properties such as references to styles and lists are translated from the original to the importing document. After the node was imported, it can be inserted into the appropriate place in the document using insertBefore(com.aspose.words.Node,com.aspose.words.Node) or insertAfter(com.aspose.words.Node,com.aspose.words.Node).

        If the source node already belongs to the destination document, then simply a deep clone of the source node is created.

        Parameters:
        srcNode - The node being imported.
        isImportChildren - True to import all child nodes recursively; otherwise, false.
        Returns:
        The cloned node that belongs to the current document.
        See Also:
        NodeImporter
      • importNode

        public Node importNode(Node srcNode, boolean isImportChildren, int importFormatMode)

        Imports a node from another document to the current document with an option to control formatting.

        This overload is useful to control how styles and list formatting are imported.

        Importing a node creates a copy of the source node belonging to the importing document. The returned node has no parent. The source node is not altered or removed from the original document.

        Before a node from another document can be inserted into this document, it must be imported. During import, document-specific properties such as references to styles and lists are translated from the original to the importing document. After the node was imported, it can be inserted into the appropriate place in the document using insertBefore(com.aspose.words.Node,com.aspose.words.Node) or insertAfter(com.aspose.words.Node,com.aspose.words.Node).

        If the source node already belongs to the destination document, then simply a deep clone of the source node is created.

        Parameters:
        srcNode - The node to imported.
        isImportChildren - True to import all child nodes recursively; otherwise, false.
        importFormatMode - A ImportFormatMode value. Specifies how to merge style formatting that clashes.
        Returns:
        The cloned, imported node. The node belongs to the destination document, but has no parent.
        See Also:
        ImportFormatMode, NodeImporter
      • indexOf

        public int indexOf(Node child)
        Returns the index of the specified child node in the child node array. Returns -1 if the node is not found in the child nodes.

        Example:

        Shows how to get the index of a given child node from its parent.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // Get the body of the first section in the document.
        Body body = doc.getFirstSection().getBody();
        // Retrieve the index of the last paragraph in the body.
        int index = body.getChildNodes().indexOf(body.getLastParagraph());

        Example:

        Retrieves the index of a row in a table.
        int rowIndex = table.indexOf(row);

        Example:

        Retrieves the index of a cell in a row.
        int cellIndex = row.indexOf(cell);
      • insertAfter

        public Node insertAfter(Node newChild, Node refChild)
        Inserts the specified node immediately after the specified reference node.

        If refChild is null, inserts newChild at the beginning of the list of child nodes.

        If the newChild is already in the tree, it is first removed.

        If the node being inserted was created from another document, you should use importNode(com.aspose.words.Node,boolean,int) to import the node to the current document. The imported node can then be inserted into the current document.

        Parameters:
        newChild - The Node to insert.
        refChild - The Node that is the reference node. The newNode is placed after the refNode.
        Returns:
        The inserted node.

        Example:

        Shows how to replace all textboxes with images.
        Document doc = new Document(getMyDir() + "Shape.ReplaceTextboxesWithImages.doc");
        
        // This gets a live collection of all shape nodes in the document.
        NodeCollection shapeCollection = doc.getChildNodes(NodeType.SHAPE, true);
        
        // Since we will be adding/removing nodes, it is better to copy all collection
        // into a fixed size array, otherwise iterator will be invalidated.
        Node[] shapes = shapeCollection.toArray();
        
        for (Node node : shapes)
        {
            Shape shape = (Shape) node;
            // Filter out all shapes that we don't need.
            if (shape.getShapeType() == ShapeType.TEXT_BOX)
            {
                // Create a new shape that will replace the existing shape.
                Shape image = new Shape(doc, ShapeType.IMAGE);
        
                // Load the image into the new shape.
                image.getImageData().setImage(getImageDir() + "Hammer.wmf");
        
                // Make new shape's position to match the old shape.
                image.setLeft(shape.getLeft());
                image.setTop(shape.getTop());
                image.setWidth(shape.getWidth());
                image.setHeight(shape.getHeight());
                image.setRelativeHorizontalPosition(shape.getRelativeHorizontalPosition());
                image.setRelativeVerticalPosition(shape.getRelativeVerticalPosition());
                image.setHorizontalAlignment(shape.getHorizontalAlignment());
                image.setVerticalAlignment(shape.getVerticalAlignment());
                image.setWrapType(shape.getWrapType());
                image.setWrapSide(shape.getWrapSide());
        
                // Insert new shape after the old shape and remove the old shape.
                shape.getParentNode().insertAfter(image, shape);
                shape.remove();
            }
        }
        
        doc.save(getMyDir() + "\\Artifacts\\Shape.ReplaceTextboxesWithImages.doc");
      • insertBefore

        public Node insertBefore(Node newChild, Node refChild)
        Inserts the specified node immediately before the specified reference node.

        If refChild is null, inserts newChild at the end of the list of child nodes.

        If the newChild is already in the tree, it is first removed.

        If the node being inserted was created from another document, you should use importNode(com.aspose.words.Node,boolean,int) to import the node to the current document. The imported node can then be inserted into the current document.

        Parameters:
        newChild - The Node to insert.
        refChild - The Node that is the reference node. The newChild is placed before this node.
        Returns:
        The inserted node.
      • iterator

        public java.util.Iterator<Node> iterator()
        Provides support for the for each style iteration over the child nodes of this node.

        Example:

        Shows how to enumerate immediate children of a CompositeNode using the enumerator provided by the ChildNodes collection.
        NodeCollection children = paragraph.getChildNodes();
        for (Node child : (Iterable<Node>) children)
        {
            // Paragraph may contain children of various types such as runs, shapes and so on.
            if (child.getNodeType() == NodeType.RUN)
            {
                // Say we found the node that we want, do something useful.
                Run run = (Run) child;
                System.out.println(run.getText());
            }
        }
      • joinRunsWithSameFormatting

        public int joinRunsWithSameFormatting()
        Joins runs with same formatting in all paragraphs of the document.

        This is an optimization method. Some documents contain adjacent runs with same formatting. Usually this occurs if a document was intensively edited manually. You can reduce the document size and speed up further processing by joining these runs.

        The operation checks every Paragraph node in the document for adjacent Run nodes having identical properties. It ignores unique identifiers used to track editing sessions of run creation and modification. First run in every joining sequence accumulates all text. Remaining runs are deleted from the document.

        Returns:
        Number of joins performed. When N adjacent runs are being joined they count as N - 1 joins.

        Example:

        Shows how to join runs in a document to reduce unneeded runs.
        // Let's load this particular document. It contains a lot of content that has been edited many times.
        // This means the document will most likely contain a large number of runs with duplicate formatting.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // This is for illustration purposes only, remember how many run nodes we had in the original document.
        int runsBefore = doc.getChildNodes(NodeType.RUN, true).getCount();
        
        // Join runs with the same formatting. This is useful to speed up processing and may also reduce redundant
        // tags when exporting to HTML which will reduce the output file size.
        int joinCount = doc.joinRunsWithSameFormatting();
        
        // This is for illustration purposes only, see how many runs are left after joining.
        int runsAfter = doc.getChildNodes(NodeType.RUN, true).getCount();
        
        System.out.println(MessageFormat.format("Number of runs before:{0}, after:{1}, joined:{2}", runsBefore, runsAfter, joinCount));
        
        // Save the optimized document to disk.
        doc.save(getMyDir() + "\\Artifacts\\Document.JoinRunsWithSameFormatting.html");
      • nextPreOrder

        public Node nextPreOrder(Node rootNode)
        Gets next node according to the pre-order tree traversal algorithm.
        Parameters:
        rootNode - The top node (limit) of traversal.
        Returns:
        Next node in pre-order order. Null if reached the rootNode.

        Example:

        Shows how to delete all images from a document using pre-order tree traversal.
        Node curNode = doc;
        while (curNode != null)
        {
            Node nextNode = curNode.nextPreOrder(doc);
        
            if (curNode.getNodeType() == NodeType.SHAPE)
            {
                Shape shape = (Shape) curNode;
        
                // Several shape types can have an image including image shapes and OLE objects.
                if (shape.hasImage()) shape.remove();
            }
        
            curNode = nextNode;
        }
      • normalizeFieldTypes

        public void normalizeFieldTypes()
        Changes field type values FieldChar.FieldType of FieldStart, FieldSeparator, FieldEnd in the whole document so that they correspond to the field types contained in the field codes.

        Use this method after document changes that affect field types.

        To change field type values in a specific part of the document use Range.normalizeFieldTypes().

      • prependChild

        public Node prependChild(Node newChild)
        Adds the specified node to the beginning of the list of child nodes for this node.

        If the newChild is already in the tree, it is first removed.

        If the node being inserted was created from another document, you should use importNode(com.aspose.words.Node,boolean,int) to import the node to the current document. The imported node can then be inserted into the current document.

        Parameters:
        newChild - The node to add.
        Returns:
        The node added.
      • previousPreOrder

        public Node previousPreOrder(Node rootNode)
        Gets the previous node according to the pre-order tree traversal algorithm.
        Parameters:
        rootNode - The top node (limit) of traversal.
        Returns:
        Previous node in pre-order order. Null if reached the rootNode.
      • print

        public void print()
        Prints the whole document to the default printer.

        Example:

        Prints the whole document to the default printer.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        doc.print();
      • print

        public void print(java.lang.String printerName)
        Print the whole document to the specified printer, using the standard (no User Interface) print controller.
        Parameters:
        printerName - The name of the printer.

        Example:

        Prints the whole document to a specified printer.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        doc.print("KONICA MINOLTA magicolor 2400W");
      • print

        public void print(javax.print.attribute.AttributeSet printerSettings)
        Prints the document according to the specified printer settings, using the standard (no User Interface) print controller.

        The javax.print.attribute.AttributeSet object allows you to specify the printer to print on, the range of pages of to print and other options.

        The javax.print.attribute.AttributeSet can contain both javax.print.attribute.PrintRequestAttribute to configure PrintJob request and javax.print.attribute.PrintServiceAttribute to configure PrintService lookup.

        Parameters:
        printerSettings - The printer settings to use.

        Example:

        Prints a range of pages.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        AttributeSet printerSettings = new HashAttributeSet();
        // Page numbers in printer settings are 1-based.
        printerSettings.add(new PageRanges(1, 3));
        
        doc.print(printerSettings);
      • print

        public void print(javax.print.attribute.AttributeSet printerSettings, java.lang.String documentName)
        Prints the document according to the specified printer settings, using the standard (no User Interface) print controller and a document name.

        The javax.print.attribute.AttributeSet object allows you to specify the printer to print on, the range of pages of to print and other options.

        The javax.print.attribute.AttributeSet can contain both javax.print.attribute.PrintRequestAttribute to configure PrintJob request and javax.print.attribute.PrintServiceAttribute to configure PrintService lookup.

        Parameters:
        printerSettings - The printer settings to use.
        documentName - The document name to display (for example, in a print status dialog box or printer queue) while printing the document.

        Example:

        Prints a range of pages along with the name of the document.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        AttributeSet printerSettings = new HashAttributeSet();
        // Page numbers in printer settings are 1-based.
        printerSettings.add(new PageRanges(1, 3));
        
        doc.print(printerSettings, "My Print Document.doc");
      • protect

        public void protect(int type)
        Protects the document from changes without changing the existing password or assigns a random password.

        When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

        When you protect a document, and the document already has a protection password, the existing protection password is not changed.

        When you protect a document, and the document does not have a protection password, this method assigns a random password that makes it impossible to unprotect the document in Microsoft Word, but you still can unprotect the document in Aspose.Words as it does not require a password when unprotecting.

        Parameters:
        type - A ProtectionType value. Specifies the protection type for the document.

        Example:

        Protects a section so only editing in form fields is possible.
        // Create a blank document
        Document doc = new Document();
        
        // Insert two sections with some text
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.writeln("Section 1. Unprotected.");
        builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
        builder.writeln("Section 2. Protected.");
        
        // Section protection only works when document protection is turned and only editing in form fields is allowed.
        doc.protect(ProtectionType.ALLOW_ONLY_FORM_FIELDS);
        
        // By default, all sections are protected, but we can selectively turn protection off.
        doc.getSections().get(0).setProtectedForForms(false);
        
        builder.getDocument().save(getMyDir() + "\\Artifacts\\Section.Protect.doc");
      • protect

        public void protect(int type, java.lang.String password)
        Protects the document from changes and optionally sets a protection password.

        When a document is protected, the user can make only limited changes, such as adding annotations, making revisions, or completing a form.

        Note that document protection is different from write protection. Write protection is specified using the WriteProtection.

        Parameters:
        type - A ProtectionType value. Specifies the protection type for the document.
        password - The password to protect the document with. Specify null or empty string if you want to protect the document without a password.

        Example:

        Shows how to protect a document.
        Document doc = new Document();
        doc.protect(ProtectionType.ALLOW_ONLY_FORM_FIELDS, "password");
      • remove

        public void remove()
        Removes itself from the parent.

        Example:

        Shows how to remove all nodes of a specific type from a composite node. In this example we remove tables from a section body.
        // Get the section that we want to work on.
        Section section = doc.getSections().get(0);
        Body body = section.getBody();
        
        // Select the first child node in the body.
        Node curNode = body.getFirstChild();
        
        while (curNode != null)
        {
            // Save the pointer to the next sibling node because if the current
            // node is removed from the parent in the next step, we will have
            // no way of finding the next node to continue the loop.
            Node nextNode = curNode.getNextSibling();
        
            // A section body can contain Paragraph and Table nodes.
            // If the node is a Table, remove it from the parent.
            if (curNode.getNodeType() == NodeType.TABLE) curNode.remove();
        
            // Continue going through child nodes until null (no more siblings) is reached.
            curNode = nextNode;
        }

        Example:

        Shows how to delete all images from a document.
        // Here we get all shapes from the document node, but you can do this for any smaller
        // node too, for example delete shapes from a single section or a paragraph.
        NodeCollection shapes = doc.getChildNodes(NodeType.SHAPE, true);
        
        // We cannot delete shape nodes while we enumerate through the collection.
        // One solution is to add nodes that we want to delete to a temporary array and delete afterwards.
        ArrayList shapesToDelete = new ArrayList();
        for (Shape shape : (Iterable<Shape>) shapes)
        {
            // Several shape types can have an image including image shapes and OLE objects.
            if (shape.hasImage()) shapesToDelete.add(shape);
        }
        
        // Now we can delete shapes.
        for (Shape shape : (Iterable<Shape>) shapesToDelete)
            shape.remove();
      • removeAllChildren

        public void removeAllChildren()
        Removes all the child nodes of the current node.

        Example:

        Creates a simple document from scratch using the Aspose.Words object model.
        // Create an "empty" document. Note that like in Microsoft Word,
        // the empty document has one section, body and one paragraph in it.
        Document doc = new Document();
        
        // This truly makes the document empty. No sections (not possible in Microsoft Word).
        doc.removeAllChildren();
        
        // Create a new section node.
        // Note that the section has not yet been added to the document,
        // but we have to specify the parent document.
        Section section = new Section(doc);
        
        // Append the section to the document.
        doc.appendChild(section);
        
        // Lets set some properties for the section.
        section.getPageSetup().setSectionStart(SectionStart.NEW_PAGE);
        section.getPageSetup().setPaperSize(PaperSize.LETTER);
        
        // The section that we created is empty, lets populate it. The section needs at least the Body node.
        Body body = new Body(doc);
        section.appendChild(body);
        
        // The body needs to have at least one paragraph.
        // Note that the paragraph has not yet been added to the document,
        // but we have to specify the parent document.
        // The parent document is needed so the paragraph can correctly work
        // with styles and other document-wide information.
        Paragraph para = new Paragraph(doc);
        body.appendChild(para);
        
        // We can set some formatting for the paragraph
        para.getParagraphFormat().setStyleName("Heading 1");
        para.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        
        // So far we have one empty paragraph in the document.
        // The document is valid and can be saved, but lets add some text before saving.
        // Create a new run of text and add it to our paragraph.
        Run run = new Run(doc);
        run.setText("Hello World!");
        run.getFont().setColor(Color.RED);
        para.appendChild(run);
        
        // As a matter of interest, you can retrieve text of the whole document and
        // see that \x000c is automatically appended. \x000c is the end of section character.
        System.out.println(doc.getText());
        
        // Save the document.
        doc.save(getMyDir() + "\\Artifacts\\Section.CreateFromScratch.doc");
      • removeChild

        public Node removeChild(Node oldChild)
        Removes the specified child node.

        The parent of oldChild is set to null after the node is removed.

        Parameters:
        oldChild - The node to remove.
        Returns:
        The removed node.

        Example:

        Demonstrates use of methods of Node and CompositeNode to remove a section before the last section in the document.
        // Document is a CompositeNode and LastChild returns the last child node in the Document node.
        // Since the Document can contain only Section nodes, the last child is the last section.
        Node lastSection = doc.getLastChild();
        
        // Each node knows its next and previous sibling nodes.
        // Previous sibling of a section is a section before the specified section.
        // If the node is the first child, PreviousSibling will return null.
        Node sectionBeforeLast = lastSection.getPreviousSibling();
        
        if (sectionBeforeLast != null) doc.removeChild(sectionBeforeLast);
      • removeExternalSchemaReferences

        public void removeExternalSchemaReferences()
        Removes external XML schema references from this document.

        Example:

        Shows how to remove all external XML schema references from a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        doc.removeExternalSchemaReferences();
      • removeMacros

        public void removeMacros()
        Removes all macros (the VBA project) as well as toolbars and command customizations from the document.

        By removing all macros from a document you can ensure the document contains no macro viruses.

        Example:

        Shows how to remove all macros from a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        doc.removeMacros();
      • removeSmartTags

        public void removeSmartTags()
        Removes all SmartTag descendant nodes of the current node. This method does not remove the content of the smart tags.

        Example:

        Removes all smart tags from descendant nodes of the composite node.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // Remove smart tags from the first paragraph in the document.
        doc.getFirstSection().getBody().getFirstParagraph().removeSmartTags();

        Example:

        Shows how to remove all smart tags from a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        doc.removeSmartTags();
      • renderToScale

        public java.awt.geom.Point2D.Float renderToScale(int pageIndex, java.awt.Graphics2D graphics, float x, float y, float scale)
                           throws java.lang.Exception
        Renders a document page into a java.awt.Graphics2D object to a specified scale.
        Parameters:
        pageIndex - The 0-based page index.
        graphics - The object where to render to.
        x - The X coordinate (in world units) of the top left corner of the rendered page.
        y - The Y coordinate (in world units) of the top left corner of the rendered page.
        scale - The scale for rendering the page (1.0 is 100%).
        Returns:
        The width and height (in world units) of the rendered page.

        Example:

        Renders individual pages to graphics to create one image with thumbnails of all pages.
        // The user opens or builds a document.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // This defines the number of columns to display the thumbnails in.
        final int THUMB_COLUMNS = 2;
        
        // Calculate the required number of rows for thumbnails.
        // We can now get the number of pages in the document.
        int thumbRows = doc.getPageCount() / THUMB_COLUMNS;
        int remainder = doc.getPageCount() % THUMB_COLUMNS;
        
        if (remainder > 0) thumbRows++;
        
        // Lets say I want thumbnails to be of this zoom.
        float SCALE = 0.25f;
        
        // For simplicity lets pretend all pages in the document are of the same size,
        // so we can use the size of the first page to calculate the size of the thumbnail.
        Dimension thumbSize = doc.getPageInfo(0).getSizeInPixels(SCALE, 96);
        
        // Calculate the size of the image that will contain all the thumbnails.
        int imgWidth = (int) (thumbSize.getWidth() * THUMB_COLUMNS);
        int imgHeight = (int) (thumbSize.getHeight() * thumbRows);
        
        BufferedImage img = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
        // The user has to provides a Graphics object to draw on.
        // The Graphics object can be created from a bitmap, from a metafile, printer or window.
        Graphics2D gr = img.createGraphics();
        try
        {
            gr.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        
        
            gr.setColor(Color.white);
            // Fill the "paper" with white, otherwise it will be transparent.
            gr.fillRect(0, 0, imgWidth, imgHeight);
        
            for (int pageIndex = 0; pageIndex < doc.getPageCount(); pageIndex++)
            {
                int rowIdx = pageIndex / THUMB_COLUMNS;
                int columnIdx = pageIndex % THUMB_COLUMNS;
        
                // Specify where we want the thumbnail to appear.
                float thumbLeft = (float) (columnIdx * thumbSize.getWidth());
                float thumbTop = (float) (rowIdx * thumbSize.getHeight());
        
                Point2D.Float size = doc.renderToScale(pageIndex, gr, thumbLeft, thumbTop, SCALE);
        
                gr.setColor(Color.black);
        
                // Draw the page rectangle.
                gr.drawRect((int) thumbLeft, (int) thumbTop, (int) size.getX(), (int) size.getY());
            }
        
            ImageIO.write(img, "PNG", new File(getMyDir() + "\\Artifacts\\Rendering.Thumbnails.png"));
        } finally
        {
            if (gr != null) gr.dispose();
        }

        Example:

        Renders a page of a Word document into a BufferedImage using a specified zoom factor.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        PageInfo pageInfo = doc.getPageInfo(0);
        
        // Let's say we want the image at 50% zoom.
        final float MY_SCALE = 0.50f;
        
        // Let's say we want the image at this resolution.
        final float MY_RESOLUTION = 200.0f;
        
        Dimension pageSize = pageInfo.getSizeInPixels(MY_SCALE, MY_RESOLUTION);
        
        BufferedImage img = new BufferedImage((int) pageSize.getWidth(), (int) pageSize.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D gr = img.createGraphics();
        
        try
        {
            // You can apply various settings to the Graphics object.
            gr.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        
            // Fill the page background.
            gr.setPaint(Color.black);
        
            // Render the page using the zoom.
            doc.renderToScale(0, gr, 0, 0, MY_SCALE);
        } finally
        {
            if (gr != null) gr.dispose();
        }
        
        ImageIO.write(img, "PNG", new File(getMyDir() + "\\Artifacts\\Rendering.RenderToScale.png"));
      • renderToSize

        public float renderToSize(int pageIndex, java.awt.Graphics2D graphics, float x, float y, float width, float height)
                          throws java.lang.Exception
        Renders a document page into a java.awt.Graphics2D object to a specified size.
        Parameters:
        pageIndex - The 0-based page index.
        graphics - The object where to render to.
        x - The X coordinate (in world units) of the top left corner of the rendered page.
        y - The Y coordinate (in world units) of the top left corner of the rendered page.
        width - The maximum width (in world units) that can be occupied by the rendered page.
        height - The maximum height (in world units) that can be occupied by the rendered page.
        Returns:
        The scale that was automatically calculated for the rendered page to fit the specified size.

        Example:

        Render to a BufferedImage at a specified location and size.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // Bitmap bmp = new Bitmap(700, 700);
        BufferedImage img = new BufferedImage(700, 700, BufferedImage.TYPE_INT_ARGB);
        // User has some sort of a Graphics object. In this case created from a bitmap.
        Graphics2D gr = img.createGraphics();
        try
        {
            // The user can specify any options on the Graphics object including
            // transform, antialiasing, page units, etc.
            gr.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        
            // The output should be offset 0.5" from the edge and rotated.
            gr.translate(ConvertUtil.inchToPoint(0.5f), ConvertUtil.inchToPoint(0.5f));
            gr.rotate(10.0 * Math.PI / 180.0, img.getWidth() / 2.0, img.getHeight() / 2.0);
        
            // Set pen color and draw our test rectangle.
            gr.setColor(Color.RED);
            gr.drawRect(0, 0, (int) ConvertUtil.inchToPoint(3), (int) ConvertUtil.inchToPoint(3));
        
            // User specifies (in world coordinates) where on the Graphics to render and what size.
            float returnedScale = doc.renderToSize(0, gr, 0f, 0f, (float) ConvertUtil.inchToPoint(3), (float) ConvertUtil.inchToPoint(3));
        
            // This is the calculated scale factor to fit 297mm into 3".
            System.out.println(MessageFormat.format("The image was rendered at {0,number,#}% zoom.", returnedScale * 100));
        
            ImageIO.write(img, "PNG", new File(getMyDir() + "\\Artifacts\\Rendering.RenderToSize.png"));
        } finally
        {
            if (gr != null) gr.dispose();
        }
      • save

        public void save(java.io.OutputStream outputStream, SaveOptions saveOptions)
                 throws java.lang.Exception
        Saves the document to a stream using the specified save options.
        Parameters:
        stream - Stream where to save the document.
        saveOptions - Specifies the options that control how the document is saved. Can be null. If this is null, the document will be saved in the binary DOC format.
        Returns:
        Additional information that you can optionally use.

        Example:

        Converts just one page (third page in this example) of the document to PDF.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        OutputStream stream = new FileOutputStream(getMyDir() + "\\Artifacts\\Rendering.SaveToPdfStreamOnePage.pdf");
        try
        {
            PdfSaveOptions options = new PdfSaveOptions();
            options.setPageIndex(2);
            options.setPageCount(1);
            doc.save(stream, options);
        } finally
        {
            if (stream != null) stream.close();
        }
      • save

        public void save(java.io.OutputStream outputStream, int saveFormat)
                 throws java.lang.Exception
        Saves the document to a stream using the specified format.
        Parameters:
        stream - Stream where to save the document.
        saveFormat - The format in which to save the document.
        Returns:
        Additional information that you can optionally use.

        Example:

        Shows how to save a document to the Jpeg format using the Save method and the ImageSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        // Save as a Jpeg image file with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.JpegDefaultOptions.jpg");
        
        // Save document to an ByteArrayOutputStream as a Jpeg with default options
        ByteArrayOutputStream docStream = new ByteArrayOutputStream();
        doc.save(docStream, SaveFormat.JPEG);
        
        // Save document to a Jpeg image with specified options.
        // Render the third page only and set the jpeg quality to 80%
        // In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
        // to signal what type of image to save as.
        ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.JPEG);
        imageOptions.setPageIndex(2);
        imageOptions.setPageCount(1);
        imageOptions.setJpegQuality(80);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.JpegCustomOptions.jpg", imageOptions);

        Example:

        Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // Option 1: Save document to file in the PDF format with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.PdfDefaultOptions.pdf");
        
        // Option 2: Save the document to stream in the PDF format with default options
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        doc.save(stream, SaveFormat.PDF);
        
        // Option 3: Save document to the PDF format with specified options
        // Render the first page only and preserve form fields as usable controls and not as plain text
        PdfSaveOptions pdfOptions = new PdfSaveOptions();
        pdfOptions.setPageIndex(0);
        pdfOptions.setPageCount(1);
        pdfOptions.setPreserveFormFields(true);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.PdfCustomOptions.pdf", pdfOptions);

        Example:

        Shows how to save a document to the Xps format using the Save method and the XpsSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        // Save document to file in the Xps format with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.XpsDefaultOptions.xps");
        
        // Save document to stream in the Xps format with default options
        ByteArrayOutputStream docStream = new ByteArrayOutputStream();
        doc.save(docStream, SaveFormat.XPS);
        
        // Save document to file in the Xps format with specified options
        // Render the first page only
        XpsSaveOptions xpsOptions = new XpsSaveOptions();
        xpsOptions.setPageIndex(0);
        xpsOptions.setPageCount(1);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.XpsCustomOptions.xps", xpsOptions);

        Example:

        Shows how to save a document to a stream.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
        doc.save(dstStream, SaveFormat.DOCX);
        
        // In you want to read the result into a Document object again, in Java you need to get the
        // data bytes and wrap into an input stream.
        ByteArrayInputStream srcStream = new ByteArrayInputStream(dstStream.toByteArray());

        Example:

        Saves a document page as a BMP image into a ByteArayOutputStream.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        doc.save(stream, SaveFormat.BMP);
        
        // The stream now contains image bytes.
        byte[] imageBytes = stream.toByteArray();
        
        // Read the bytes back into an image.
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
      • save

        public SaveOutputParameters save(java.lang.String fileName)
                                 throws java.lang.Exception
        Saves the document to a file. Automatically determines the save format from the extension.
        Parameters:
        fileName - The name for the document. If a document with the specified file name already exists, the existing document is overwritten.
        Returns:
        Additional information that you can optionally use.

        Example:

        Shows how to save a document to the Jpeg format using the Save method and the ImageSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        // Save as a Jpeg image file with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.JpegDefaultOptions.jpg");
        
        // Save document to an ByteArrayOutputStream as a Jpeg with default options
        ByteArrayOutputStream docStream = new ByteArrayOutputStream();
        doc.save(docStream, SaveFormat.JPEG);
        
        // Save document to a Jpeg image with specified options.
        // Render the third page only and set the jpeg quality to 80%
        // In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
        // to signal what type of image to save as.
        ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.JPEG);
        imageOptions.setPageIndex(2);
        imageOptions.setPageCount(1);
        imageOptions.setJpegQuality(80);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.JpegCustomOptions.jpg", imageOptions);

        Example:

        Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // Option 1: Save document to file in the PDF format with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.PdfDefaultOptions.pdf");
        
        // Option 2: Save the document to stream in the PDF format with default options
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        doc.save(stream, SaveFormat.PDF);
        
        // Option 3: Save document to the PDF format with specified options
        // Render the first page only and preserve form fields as usable controls and not as plain text
        PdfSaveOptions pdfOptions = new PdfSaveOptions();
        pdfOptions.setPageIndex(0);
        pdfOptions.setPageCount(1);
        pdfOptions.setPreserveFormFields(true);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.PdfCustomOptions.pdf", pdfOptions);

        Example:

        Shows how to save a document to the Xps format using the Save method and the XpsSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        // Save document to file in the Xps format with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.XpsDefaultOptions.xps");
        
        // Save document to stream in the Xps format with default options
        ByteArrayOutputStream docStream = new ByteArrayOutputStream();
        doc.save(docStream, SaveFormat.XPS);
        
        // Save document to file in the Xps format with specified options
        // Render the first page only
        XpsSaveOptions xpsOptions = new XpsSaveOptions();
        xpsOptions.setPageIndex(0);
        xpsOptions.setPageCount(1);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.XpsCustomOptions.xps", xpsOptions);

        Example:

        Converts a whole document to PDF using default options.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        doc.save(getMyDir() + "\\Artifacts\\Rendering.SaveToPdfDefault.pdf");

        Example:

        Converts from DOC to MHTML format.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        doc.save(getMyDir() + "\\Artifacts\\Document.ConvertToMhtml.mht");

        Example:

        Converts a whole document from DOC to PDF using default options.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        doc.save(getMyDir() + "\\Artifacts\\Document.Doc2PdfSave.pdf");

        Example:

        Saves a document to a file.
        doc.save(getMyDir() + "\\Artifacts\\Document.OpenFromFile.doc");
      • save

        public SaveOutputParameters save(java.lang.String fileName, SaveOptions saveOptions)
                                 throws java.lang.Exception
        Saves the document to a file using the specified save options.
        Parameters:
        fileName - The name for the document. If a document with the specified file name already exists, the existing document is overwritten.
        saveOptions - Specifies the options that control how the document is saved. Can be null.
        Returns:
        Additional information that you can optionally use.

        Example:

        Shows how to save a document to the Jpeg format using the Save method and the ImageSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        // Save as a Jpeg image file with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.JpegDefaultOptions.jpg");
        
        // Save document to an ByteArrayOutputStream as a Jpeg with default options
        ByteArrayOutputStream docStream = new ByteArrayOutputStream();
        doc.save(docStream, SaveFormat.JPEG);
        
        // Save document to a Jpeg image with specified options.
        // Render the third page only and set the jpeg quality to 80%
        // In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor
        // to signal what type of image to save as.
        ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.JPEG);
        imageOptions.setPageIndex(2);
        imageOptions.setPageCount(1);
        imageOptions.setJpegQuality(80);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.JpegCustomOptions.jpg", imageOptions);

        Example:

        Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // Option 1: Save document to file in the PDF format with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.PdfDefaultOptions.pdf");
        
        // Option 2: Save the document to stream in the PDF format with default options
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        doc.save(stream, SaveFormat.PDF);
        
        // Option 3: Save document to the PDF format with specified options
        // Render the first page only and preserve form fields as usable controls and not as plain text
        PdfSaveOptions pdfOptions = new PdfSaveOptions();
        pdfOptions.setPageIndex(0);
        pdfOptions.setPageCount(1);
        pdfOptions.setPreserveFormFields(true);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.PdfCustomOptions.pdf", pdfOptions);

        Example:

        Shows how to save a document to the Xps format using the Save method and the XpsSaveOptions class.
        // Open the document
        Document doc = new Document(getMyDir() + "Rendering.doc");
        // Save document to file in the Xps format with default options
        doc.save(getMyDir() + "\\Artifacts\\Rendering.XpsDefaultOptions.xps");
        
        // Save document to stream in the Xps format with default options
        ByteArrayOutputStream docStream = new ByteArrayOutputStream();
        doc.save(docStream, SaveFormat.XPS);
        
        // Save document to file in the Xps format with specified options
        // Render the first page only
        XpsSaveOptions xpsOptions = new XpsSaveOptions();
        xpsOptions.setPageIndex(0);
        xpsOptions.setPageCount(1);
        doc.save(getMyDir() + "\\Artifacts\\Rendering.XpsCustomOptions.xps", xpsOptions);

        Example:

        Converts every page of a DOC file into a separate scalable EMF file.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        ImageSaveOptions options = new ImageSaveOptions(SaveFormat.EMF);
        options.setPageCount(1);
        
        for (int i = 0; i < doc.getPageCount(); i++)
        {
            options.setPageIndex(i);
            doc.save(getMyDir() + "\\Artifacts\\Rendering.SaveToEmf." + Integer.toString(i) + ".emf", options);
        }

        Example:

        Converts a whole document to PDF with three levels in the document outline.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        PdfSaveOptions options = new PdfSaveOptions();
        options.getOutlineOptions().setHeadingsOutlineLevels(3);
        options.getOutlineOptions().setExpandedOutlineLevels(1);
        
        doc.save(getMyDir() + "\\Artifacts\\Rendering.SaveToPdfWithOutline.pdf", options);
      • save

        public SaveOutputParameters save(java.lang.String fileName, int saveFormat)
                                 throws java.lang.Exception
        Saves the document to a file in the specified format.
        Parameters:
        fileName - The name for the document. If a document with the specified file name already exists, the existing document is overwritten.
        saveFormat - A SaveFormat value. The format in which to save the document.
        Returns:
        Additional information that you can optionally use.

        Example:

        Converts from DOC to HTML format.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        doc.save(getMyDir() + "\\Artifacts\\Document.ConvertToHtml.html", SaveFormat.HTML);
      • selectNodes

        public NodeList selectNodes(java.lang.String xpath)
        Selects a list of nodes matching the XPath expression.

        Only expressions with element names are supported at the moment. Expressions that use attribute names are not supported.

        Parameters:
        xpath - The XPath expression.
        Returns:
        A list of nodes matching the XPath query.

        Example:

        Shows how to test if a node is inside a field by using an XPath expression.
        // Let's pick a document we know has some fields in.
        Document doc = new Document(getMyDir() + "MailMerge.MergeImage.doc");
        
        // Let's say we want to check if the Run below is inside a field.
        Run run = (Run) doc.getChild(NodeType.RUN, 5, true);
        
        // Evaluate the XPath expression. The resulting NodeList will contain all nodes found inside a field a field (between FieldStart
        // and FieldEnd exclusive). There can however be FieldStart and FieldEnd nodes in the list if there are nested fields
        // in the path. Currently does not find rare fields in which the FieldCode or FieldResult spans across multiple paragraphs.
        NodeList resultList = doc.selectNodes("//FieldStart/following-sibling::node()[following-sibling::FieldEnd]");
        
        // Check if the specified run is one of the nodes that are inside the field.
        for (Node node : (Iterable<Node>) resultList)
        {
            if (node == run)
            {
                System.out.println("The node is found inside a field");
                break;
            }
        }

        Example:

        Shows how to select certain nodes by using an XPath expression.
        Document doc = new Document(getMyDir() + "Table.Document.doc");
        
        // This expression will extract all paragraph nodes which are descendants of any table node in the document.
        // This will return any paragraphs which are in a table.
        NodeList nodeList = doc.selectNodes("//Table//Paragraph");
        
        // This expression will select any paragraphs that are direct children of any body node in the document.
        nodeList = doc.selectNodes("//Body/Paragraph");
        
        // Use SelectSingleNode to select the first result of the same expression as above.
        Node node = doc.selectSingleNode("//Body/Paragraph");
      • selectSingleNode

        public Node selectSingleNode(java.lang.String xpath)
        Selects the first Node that matches the XPath expression.

        Only expressions with element names are supported at the moment. Expressions that use attribute names are not supported.

        Parameters:
        xpath - The XPath expression.
        Returns:
        The first Node that matches the XPath query or null if no matching node is found.

        Example:

        Shows how to select certain nodes by using an XPath expression.
        Document doc = new Document(getMyDir() + "Table.Document.doc");
        
        // This expression will extract all paragraph nodes which are descendants of any table node in the document.
        // This will return any paragraphs which are in a table.
        NodeList nodeList = doc.selectNodes("//Table//Paragraph");
        
        // This expression will select any paragraphs that are direct children of any body node in the document.
        nodeList = doc.selectNodes("//Body/Paragraph");
        
        // Use SelectSingleNode to select the first result of the same expression as above.
        Node node = doc.selectSingleNode("//Body/Paragraph");
      • startTrackRevisions

        public void startTrackRevisions(java.lang.String author)
        Starts automatically marking all further changes you make to the document programmatically as revision changes.

        If you call this method and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.

        Currently Aspose.Words supports tracking of node insertions and deletions only. Formatting changes are not recorded as revisions.

        Automatic tracking of changes is supported both when modifying this document through node manipulations as well as when using DocumentBuilder

        This method does not change the TrackRevisions option and does not use its value for the purposes of revision tracking.

        Parameters:
        author - Initials of the author to use for revisions.
        See Also:
        stopTrackRevisions()

        Example:

        Shows how tracking revisions affects document editing.
        Document doc = new Document();
        
        // This text will appear as normal text in the document and no revisions will be counted.
        doc.getFirstSection().getBody().getFirstParagraph().getRuns().add(new Run(doc, "Hello world!"));
        System.out.println(doc.getRevisions().getCount()); // 0
        
        doc.startTrackRevisions("Author");
        
        // This text will appear as a revision. 
        // We did not specify a time while calling StartTrackRevisions(), so the date/time that's noted
        // on the revision will be the real time when StartTrackRevisions() executes.
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 2
        
        // Stopping the tracking of revisions makes this text appear as normal text. 
        // Revisions are not counted when the document is changed.
        doc.stopTrackRevisions();
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 2
        
        // Specifying some date/time will apply that date/time to all subsequent revisions until StopTrackRevisions() is called.
        // Note that placing values such as DateTime.MinValue as an argument will create revisions that do not have a date/time at all.
        doc.startTrackRevisions("Author", new SimpleDateFormat("yyyy/MM/DD").parse("1970/01/01"));
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 4
        
        doc.save(getMyDir() + "\\Artifacts\\Document.StartTrackRevisions.doc");
      • startTrackRevisions

        public void startTrackRevisions(java.lang.String author, java.util.Date dateTime)
        Starts automatically marking all further changes you make to the document programmatically as revision changes.

        If you call this method and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.

        Currently Aspose.Words supports tracking of node insertions and deletions only. Formatting changes are not recorded as revisions.

        Automatic tracking of changes is supported both when modifying this document through node manipulations as well as when using DocumentBuilder

        This method does not change the TrackRevisions option and does not use its value for the purposes of revision tracking.

        Parameters:
        author - Initials of the author to use for revisions.
        dateTime - The date and time to use for revisions.
        See Also:
        stopTrackRevisions()

        Example:

        Shows how tracking revisions affects document editing.
        Document doc = new Document();
        
        // This text will appear as normal text in the document and no revisions will be counted.
        doc.getFirstSection().getBody().getFirstParagraph().getRuns().add(new Run(doc, "Hello world!"));
        System.out.println(doc.getRevisions().getCount()); // 0
        
        doc.startTrackRevisions("Author");
        
        // This text will appear as a revision. 
        // We did not specify a time while calling StartTrackRevisions(), so the date/time that's noted
        // on the revision will be the real time when StartTrackRevisions() executes.
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 2
        
        // Stopping the tracking of revisions makes this text appear as normal text. 
        // Revisions are not counted when the document is changed.
        doc.stopTrackRevisions();
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 2
        
        // Specifying some date/time will apply that date/time to all subsequent revisions until StopTrackRevisions() is called.
        // Note that placing values such as DateTime.MinValue as an argument will create revisions that do not have a date/time at all.
        doc.startTrackRevisions("Author", new SimpleDateFormat("yyyy/MM/DD").parse("1970/01/01"));
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 4
        
        doc.save(getMyDir() + "\\Artifacts\\Document.StartTrackRevisions.doc");
      • stopTrackRevisions

        public void stopTrackRevisions()
        Stops automatic marking of document changes as revisions.
        See Also:
        startTrackRevisions(java.lang.String,java.util.Date)

        Example:

        Shows how tracking revisions affects document editing.
        Document doc = new Document();
        
        // This text will appear as normal text in the document and no revisions will be counted.
        doc.getFirstSection().getBody().getFirstParagraph().getRuns().add(new Run(doc, "Hello world!"));
        System.out.println(doc.getRevisions().getCount()); // 0
        
        doc.startTrackRevisions("Author");
        
        // This text will appear as a revision. 
        // We did not specify a time while calling StartTrackRevisions(), so the date/time that's noted
        // on the revision will be the real time when StartTrackRevisions() executes.
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 2
        
        // Stopping the tracking of revisions makes this text appear as normal text. 
        // Revisions are not counted when the document is changed.
        doc.stopTrackRevisions();
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 2
        
        // Specifying some date/time will apply that date/time to all subsequent revisions until StopTrackRevisions() is called.
        // Note that placing values such as DateTime.MinValue as an argument will create revisions that do not have a date/time at all.
        doc.startTrackRevisions("Author", new SimpleDateFormat("yyyy/MM/DD").parse("1970/01/01"));
        doc.getFirstSection().getBody().appendParagraph("Hello again!");
        System.out.println(doc.getRevisions().getCount()); // 4
        
        doc.save(getMyDir() + "\\Artifacts\\Document.StartTrackRevisions.doc");
      • toString

        public java.lang.String toString(SaveOptions saveOptions)
                       throws java.lang.Exception
        Exports the content of the node into a string using the specified save options.
        Parameters:
        saveOptions - Specifies the options that control how the node is saved.
        Returns:
        The content of the node in the specified format.

        Example:

        Exports the content of a node to string in HTML format using custom specified options.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // Extract the last paragraph in the document to convert to HTML.
        Node node = doc.getLastSection().getBody().getLastParagraph();
        
        // Create an instance of HtmlSaveOptions and set a few options.
        HtmlSaveOptions saveOptions = new HtmlSaveOptions();
        saveOptions.setExportHeadersFootersMode(ExportHeadersFootersMode.PER_SECTION);
        saveOptions.setExportRelativeFontSize(true);
        
        // Convert the document to HTML and return as a string. Pass the instance of HtmlSaveOptions to
        // to use the specified options during the conversion.
        String nodeAsHtml = node.toString(saveOptions);
      • toString

        public java.lang.String toString(int saveFormat)
                       throws java.lang.Exception
        Exports the content of the node into a string in the specified format.
        Returns:
        The content of the node in the specified format.
        Parameters:
        saveFormat - A SaveFormat value.

        Example:

        Shows how to extract the label of each paragraph in a list as a value or a String.
        Document doc = new Document(getMyDir() + "Lists.PrintOutAllLists.doc");
        doc.updateListLabels();
        int listParaCount = 1;
        
        for (Paragraph paragraph : (Iterable<Paragraph>) doc.getChildNodes(NodeType.PARAGRAPH, true))
        {
            // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
            // which start at three and ends at six.
            if (paragraph.getListFormat().isListItem())
            {
                System.out.println(MessageFormat.format("Paragraph #{0}", listParaCount));
        
                // This is the text we get when actually getting when we output this node to text format.
                // The list labels are not included in this text output. Trim any paragraph formatting characters.
                String paragraphText = paragraph.toString(SaveFormat.TEXT).trim();
                System.out.println("Exported Text: " + paragraphText);
        
                ListLabel label = paragraph.getListLabel();
                // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
                // will tell us what position it is on that particular level.
                System.out.println("Numerical Id: " + label.getLabelValue());
        
                // Combine them together to include the list label with the text in the output.
                System.out.println("List label combined with text: " + label.getLabelString() + " " + paragraphText);
        
                listParaCount++;
            }
        }

        Example:

        Shows the difference between calling the GetText and ToString methods on a node.
        Document doc = new Document();
        
        // Enter a dummy field into the document.
        DocumentBuilder builder = new DocumentBuilder(doc);
        builder.insertField("MERGEFIELD Field");
        
        // GetText will retrieve all field codes and special characters
        System.out.println("GetText() Result: " + doc.getText());
        
        // ToString will export the node to the specified format. When converted to text it will not retrieve fields code
        // or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
        // This is the same as "viewing" the document as if it was opened in a text editor.
        System.out.println("ToString() Result: " + doc.toString(SaveFormat.TEXT));

        Example:

        Exports the content of a node to string in HTML format using default options.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // Extract the last paragraph in the document to convert to HTML.
        Node node = doc.getLastSection().getBody().getLastParagraph();
        
        // When ToString is called using the SaveFormat overload then conversion is executed using default save options.
        // When saving to HTML using default options the following settings are set:
        //   ExportImagesAsBase64 = true
        //   CssStyleSheetType = CssStyleSheetType.Inline
        //   ExportFontResources = false
        String nodeAsHtml = node.toString(SaveFormat.HTML);
      • unlinkFields

        public void unlinkFields()
                         throws java.lang.Exception
        Unlinks fields in the whole document.

        Replaces all the fields in the whole document with their most recent results.

        To unlink fields in a specific part of the document use Range.unlinkFields().

        Example:

        Shows how to unlink all fields in the document
        Document doc = new Document(getMyDir() + "Field.UnlinkFields.docx");
        
        doc.unlinkFields();
      • unprotect

        public void unprotect()
        Removes protection from the document regardless of the password.

        This method unprotects the document even if it has a protection password.

        Note that document protection is different from write protection. Write protection is specified using the WriteProtection.

        Example:

        Shows how to unprotect any document. Note that the password is not required.
        doc.unprotect();
      • unprotect

        public boolean unprotect(java.lang.String password)
        Removes protection from the document if a correct password is specified.

        This method unprotects the document only if a correct password is specified.

        Note that document protection is different from write protection. Write protection is specified using the WriteProtection.

        Parameters:
        password - The password to unprotect the document with.
        Returns:
        True if a correct password was specified and the document was unprotected.

        Example:

        Shows how to unprotect a document using a password.
        doc.unprotect("password");
      • updateFields

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

        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 updatePageLayout().

        Use the normalizeFieldTypes() method before fields updating if there were document changes that affected field types.

        To update fields in a specific part of the document use Range.updateFields().

        Example:

        Demonstrates how to insert a Table of contents (TOC) into a document using heading styles as entries.
        // Use a blank document
        Document doc = new Document();
        // Create a document builder to insert content with into document.
        DocumentBuilder builder = new DocumentBuilder(doc);
        // Insert a table of contents at the beginning of the document.
        builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");
        // Start the actual document content on the second page.
        builder.insertBreak(BreakType.PAGE_BREAK);
        // Build a document with complex structure by applying different heading styles thus creating TOC entries.
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
        
        builder.writeln("Heading 1");
        
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);
        
        builder.writeln("Heading 1.1");
        builder.writeln("Heading 1.2");
        
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
        
        builder.writeln("Heading 2");
        builder.writeln("Heading 3");
        
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);
        
        builder.writeln("Heading 3.1");
        
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_3);
        
        builder.writeln("Heading 3.1.1");
        builder.writeln("Heading 3.1.2");
        builder.writeln("Heading 3.1.3");
        
        builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2);
        
        builder.writeln("Heading 3.2");
        builder.writeln("Heading 3.3");
        
        // Call the method below to update the TOC.
        doc.updateFields();

        Example:

        Shows how to update all fields before rendering a document.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // This updates all fields in the document.
        doc.updateFields();
        
        doc.save(getMyDir() + "\\Artifacts\\Rendering.UpdateFields.pdf");

        Example:

        Shows how to update all fields in a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        doc.updateFields();
      • updateListLabels

        public void updateListLabels()
                             throws java.lang.Exception
        Updates list labels for all list items in the document.

        This method updates list label properties such as ListLabel.LabelValue and ListLabel.LabelString for each Paragraph.ListLabel object in the document.

        Also, this method is sometimes implicitly called when updating fields in the document. This is required because some fields that may reference list numbers (such as TOC or REF) need them be up-to-date.

        Example:

        Shows how to extract the label of each paragraph in a list as a value or a String.
        Document doc = new Document(getMyDir() + "Lists.PrintOutAllLists.doc");
        doc.updateListLabels();
        int listParaCount = 1;
        
        for (Paragraph paragraph : (Iterable<Paragraph>) doc.getChildNodes(NodeType.PARAGRAPH, true))
        {
            // Find if we have the paragraph list. In our document our list uses plain arabic numbers,
            // which start at three and ends at six.
            if (paragraph.getListFormat().isListItem())
            {
                System.out.println(MessageFormat.format("Paragraph #{0}", listParaCount));
        
                // This is the text we get when actually getting when we output this node to text format.
                // The list labels are not included in this text output. Trim any paragraph formatting characters.
                String paragraphText = paragraph.toString(SaveFormat.TEXT).trim();
                System.out.println("Exported Text: " + paragraphText);
        
                ListLabel label = paragraph.getListLabel();
                // This gets the position of the paragraph in current level of the list. If we have a list with multiple level then this
                // will tell us what position it is on that particular level.
                System.out.println("Numerical Id: " + label.getLabelValue());
        
                // Combine them together to include the list label with the text in the output.
                System.out.println("List label combined with text: " + label.getLabelString() + " " + paragraphText);
        
                listParaCount++;
            }
        }
      • updatePageLayout

        public void updatePageLayout()
                             throws java.lang.Exception
        Rebuilds the page layout of the document.

        This method formats a document into pages and updates the page number related fields in the document such as PAGE, PAGES, PAGEREF and REF. The up-to-date page layout information is required for a correct rendering of the document to fixed-page formats.

        This method is automatically invoked when you first convert a document to PDF, XPS, image or print it. However, if you modify the document after rendering and then attempt to render it again - Aspose.Words will not update the page layout automatically. In this case you should call updatePageLayout() before rendering again.

        Example:

        Shows when to request page layout of the document to be recalculated.
        Document doc = new Document(getMyDir() + "Rendering.doc");
        
        // Saving a document to PDF or to image or printing for the first time will automatically
        // layout document pages and this information will be cached inside the document.
        doc.save(getMyDir() + "\\Artifacts\\Rendering.UpdatePageLayout1.pdf");
        
        // Modify the document in any way.
        doc.getStyles().get("Normal").getFont().setSize(6);
        doc.getSections().get(0).getPageSetup().setOrientation(com.aspose.words.Orientation.LANDSCAPE);
        
        // In the current version of Aspose.Words, modifying the document does not automatically rebuild
        // the cached page layout. If you want to save to PDF or render a modified document again,
        // you need to manually request page layout to be updated.
        doc.updatePageLayout();
        
        doc.save(getMyDir() + "\\Artifacts\\Rendering.UpdatePageLayout2.pdf");
      • updateTableLayout

        public void updateTableLayout()
        Updates widths of cells and tables in the document according to their preferred widths and content. You do not need to call this method if the tables appear correct in the output document.

        You do not normally need to call this method as cell and table widths are maintained automatically. You can call this method before exporting to PDF (or any other fixed-page format), only in rare cases where you confirmed that tables appear incorrectly laid out in the output document. Calling this method might help to correct the output.

        Example:

        Shows how to update the layout of tables in a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // Normally this method is not necessary to call, as cell and table widths are maintained automatically.
        // This method may need to be called when exporting to PDF in rare cases when the table layout appears
        // incorrectly in the rendered output.
        doc.updateTableLayout();
      • updateThumbnail

        public void updateThumbnail()
                            throws java.lang.Exception
        Updates BuiltInDocumentProperties.Thumbnail of the document using default options.

        Example:

        Shows how to update a document's thumbnail.
        Document doc = new Document();
        
        // Update document's thumbnail the default way. 
        doc.updateThumbnail();
        
        // Review/change thumbnail options and then update document's thumbnail.
        ThumbnailGeneratingOptions tgo = new ThumbnailGeneratingOptions();
        
        System.out.println(MessageFormat.format("Thumbnail size: {0}", tgo.getThumbnailSize()));
        tgo.setGenerateFromFirstPage(true);
        
        doc.updateThumbnail(tgo);
      • updateThumbnail

        public void updateThumbnail(ThumbnailGeneratingOptions options)
                            throws java.lang.Exception
        Updates BuiltInDocumentProperties.Thumbnail of the document according to the specified options. The ThumbnailGeneratingOptions allows you to specify the source of thumbnail, size and other options. If attempt to generate thumbnail fails, doesn't change one.
        Parameters:
        options - The generating options to use.

        Example:

        Shows how to update a document's thumbnail.
        Document doc = new Document();
        
        // Update document's thumbnail the default way. 
        doc.updateThumbnail();
        
        // Review/change thumbnail options and then update document's thumbnail.
        ThumbnailGeneratingOptions tgo = new ThumbnailGeneratingOptions();
        
        System.out.println(MessageFormat.format("Thumbnail size: {0}", tgo.getThumbnailSize()));
        tgo.setGenerateFromFirstPage(true);
        
        doc.updateThumbnail(tgo);
      • updateWordCount

        public void updateWordCount()
                            throws java.lang.Exception
        Updates word count properties of the document.

        UpdateWordCount recalculates and updates Characters, Words and Paragraphs properties in the BuiltInDocumentProperties collection of the Document.

        Note that UpdateWordCount does not update number of lines and pages properties. Use the updateWordCount() overload and pass True value as a parameter to do that.

        When you use an evaluation version, the evaluation watermark will also be included in the word count.

        Example:

        Shows how to update all list labels in a document.
        Document doc = new Document(getMyDir() + "Document.doc");
        
        // Some work should be done here that changes the document's content.
        
        // Update the word, character and paragraph count of the document.
        doc.updateWordCount();
        
        // Display the updated document properties.
        System.out.println(MessageFormat.format("Characters: {0}", doc.getBuiltInDocumentProperties().getCharacters()));
        System.out.println(MessageFormat.format("Words: {0}", doc.getBuiltInDocumentProperties().getWords()));
        System.out.println(MessageFormat.format("Paragraphs: {0}", doc.getBuiltInDocumentProperties().getParagraphs()));
      • updateWordCount

        public void updateWordCount(boolean updateLinesCount)
                            throws java.lang.Exception
        Updates word count properties of the document, optionally updates BuiltInDocumentProperties.Lines property. This method will rebuild page layout of the document.
        Parameters:
        updateLinesCount - True if number of lines in the document shall be calculated.