Documents > Cookbook >Text Document

Till now, we support high level APIs to manipulate text document, paragraph, section, list, footer, header, textbox and span.

Generate TextDocument
There are typically four kinds of Text Documents with different modes can be generated: text document, master document, template document and web document.
The following codes generates an empty text document.

            TextDocument document1=TextDocument.newTextDocument();;

There are two methods to generate a new document, one with a parameter of OdfMediaType, and the other one just use the corresponding new function.
The following two lines of codes generate the same kinds of document(Master document). The other three kinds of document are similar.

        TextDocument documentMedia1=TextDocument.newTextDocument(OdfMediaType.TEXT_MASTER);
TextDocument documentMedia2=TextDocument.newTextMasterDocument();

Get TextDocument
We can get the existing Text Document by using the loadDocument function like follows. The loadDocument function has four kinds of parameters: File, InputStream, OdfPackageDocument and String. Here the one with string parameter is used as an example.

        TextDocument document2=(TextDocument)TextDocument.loadDocument("textdocument.odt");

Also we can change the mode of one text document by using the following codes:


Insert TextDocument
From version 0.8, you can copy contents from a source TextDocument and then insert them to the current TextDocument. The insert position is relative to a reference Paragraph, before or after. You can also choose to copy the styles with the contents or not.

        TextDocument src = TextDocument.loadDocument("SourceDocument.odt");
        TextDocument target = TextDocument.loadDocument("TargetDocument.odt");
        Paragraph p1 = target.getParagraphByIndex(0, true);
        // insert contents before p1 and copy styles
        target.insertContentFromDocumentBefore(src, p1, true);
        // insert contents after p1 and don't copy styles
        target.insertContentFromDocumentAfter(src, p1, false);

To add a new paragraph to a text document, the following codes can be used, the first one add an empty paragraph to the end of the document, and the second one add a new paragraph with the corresponding texts to the document.

document1.addParagraph("test newParagraph function in textDocument");

The first one will get the second paragraph of this document. The second statement will get the last paragraph with text content. The paragraph without text content will be ignored if the second parameter is true.
The following codes can be used to append text to the end of a paragrah.

        para1.appendTextContent("test addText function in textDocument");

The following codes are to get and set the horizontal alignment of a paragraph.

        HorizontalAlignmentType align = para1.getHorizontalAlignment();

The following codes are to get and set the font of a paragraph.

        Font font = para1.getFont();

The following code is to apply a hyperlink to this paragraph, and append a text with a hyperlink to this paragraph.

        para2.applyHyperlink(new URI(""));
para2.appendHyperlink("mail to me",new URI(""));

The following code is to add a comment at the front of the paragraph.

        para2.addComment("This is a comment for para2", "Simple ODF Commenter");

From version 0.6.5, we support heading feature. You can test whether a paragraph is heading, apply a plain text paragraph as heading, and get heading level.

     // isHeading() and getHeadingLevel();
        if (para2.isHeading()) {
int headingLevel = para2.getHeadingLevel();
System.out.println("para2 is a heading, its level is " + headingLevel + ".");
// applyHeading(), default level is 1. para1.applyHeading();
// applyHeading(), heading level is 3. para1.applyHeading(true, 3);

From version 0.4, we support high level APIs for section. You can use the following code to get a section by name:

        Section aSection = document1.getSectionByName("ImageSection");

or use the following code to get an iterator of sections. All sections in the document would be returned, including sections in footer and header.

        Iterator<Section> sections = document1.getSectionIterator();
while (sections.hasNext()) {
Section theSection =;

After you get the object of section, you can use the following codes to set and get the name of the section.

        String name = aSection.getName();

You can use the following code to copy and append a section at the end of a document. Copying from a foreign document is supported. You don't need to care whether or not the document is the owner of the source section.

        document1.appendSection(aSection, true);

If you want to copy and append a section within a same document, you can specify with the second parameter of "copyAppendSection(Section section, boolean isResourceCopied)" whether the linked resources to this section are copied or not. The following code means to copy a section and append it at the end, but the linked resources are shared between the source section and the copied section.

        document1.appendSection(aSection, false);

You can remove this Section from the document content, all the resources that are only linked with this section would be removed too.


From version 0.8, we support high level APIs to protect a section. You can use the following code to set the protection without a password:


If you want to protect a section with a password, you can use the following code.


From version 0.4, we support high level APIs for list. You can use the following code to create a list. The two methods are same.

        List newList1 = document1.addList();
List newList2 = new List(document1);

Actually, you can append list to table cell, list item, presentation slide and notes. They all have the same ability with text document for list. We call them ListContainer, which can append, remove and get the iterator of list.

        Iterator<List> lists = document1.getListIterator();
List list =null;
while (lists.hasNext()) {
list =;

After you get the object of list, you can use the following methods to set and get the header of the list.

        String header = list.getHeader();

You can get all of the existing items in this list. They are returned as java.util.List.

        java.util.List<ListItem> items = list.getItems();

If you only want to get the item at a specific location, you can use the following code:

        int location = 2;
ListItem item = list.getItem(location);

There are several ways to help you append item(s) to the list. Please reference the following code:

     // add single item
        ListItem newItem1 = list.addItem(item);
ListItem newItem2 = list.addItem("itemContent");
// add clone items ListItem[] newItems = new ListItem[]{newItem1, newItem2};
// add string items String[] newItemContents = new String[]{"itemContent1", "itemContent2"};

You can specify a location to insert new item(s).

        newItem1 = list.addItem(location, item);
newItem2 = list.addItem(location, "itemContent");
list.addItems(location, newItems);
list.addItems(location, newItemContents);

If you want to replace a list item with a new one, you can use the following code.

        item = list.set(location, newItem1);
item = list.set(location, "itemContent");

You can use the following methods to remove item(s).

//item in specific location. list.removeItem(location);
//item in specific collection. list.removeItems(items);

You can specify with the following methods whether the numbering of the previous list is continued by this list:

     // the numbering of the proximate list is continued
// the numbering of the specified list is continued by this list newList2.setContinueList(list);

You can use the following method to know whether the list is a number list.

        ListType type = list.getType();

Now, List API support 3 types of lists, ListType.BULLET, ListType.NUMBER and ListType.IMAGE. The default created list is ListType.BULLET, bullet list. How to create a number list or a image list then? ListDecorator has powerful functions that can help you. ListDecorator is an interface which decides how to decorate a list and its list items. We supply 4 implementations of this interface, BulletDecorator, NumberDecorator, ImageDecorator and OutlineDecorator.

     // create a number list.
        ListDecorator numberDecorator = new NumberDecorator(document1);
List numberList1 = document1.addList(numberDecorator);
List numberList2 = new List(document1, numberDecorator);

You can implement your own ListDecorator as need, or extend the default four implementations.
You can remove a list from the document, the following two methods are same.


We also provide funtions to manipulate list items. You can use the following methods to get and set the text content of a item.

        String itemContent = item.getTextContent();
item.setTextContent("new item content");

You can get the item index and its owner list.

        int index = item.getIndex();
List ownerList = item.getOwnerList();

When you want to remove an item, besides List.removeItem(ListItem), you can use the following method directly.


With the help of the following code, the start number of list item can be set.


Since list item is also a ListContainer, you can add sub list to an item.


Header and Footer
From version 0.4.5, we support high level APIs for footer and header. You can use the following code to get the header and footer.

        Header docHeader = doc.getHeader();
Footer footer = doc.getFooter();

In order to add contents to header and arrange these contents in a good layout, I suggest you to use table. It's easy to add a none-border table to header. Below codes show how to add a table with 2 columns and 1 row to header, and then add some text content to the left cell, and add an image to the right cell.

        Table table = docHeader.addTable(1,2);
table.getCellByPosition(0, 0).setStringValue("header table cell");
Cell cell = table.getCellByPosition(1, 0);
Image image1 = cell.setImage(new URI("file:/c:/image.jpg"));

Below codes show how to add a table with 1 column and 1 row to footer, and then add some text content to the cell. You can easily set the style of these text content. The codes describe how to put the text content in the center, set the font of the text content, and set the background of the cell.

        table = footer.addTable(1, 1);
Cell cellByPosition = table.getCellByPosition(0, 0);
cellByPosition.setStringValue("footer table cell");
Font myFont = new Font("Arial", StyleTypeDefinitions.FontStyle.ITALIC, 12, Color.BLUE);

Text Box
From version 0.5, we support high level APIs for text box. Below codes will create a text box and add it to the text document with a paragraph as the anchor position. The FrameRectangle specifies an area and the position of this text box.

        Paragraph paragraph = doc.getParagraphByIndex(0, false);
Textbox box = paragraph.addTextbox(new FrameRectangle(1,1,2,1,SupportedLinearMeasure.IN));

Below codes is to set the text content and name of this text box;

        box.setTextContent("this is a text box");

Below codes is to get a text box by name or get an iterator of text box contained by a paragraph.

        Textbox myBox=paragraph.getTextboxByName("MyTextbox");
Iterator<Textbox> boxIter = paragraph.getTextboxIterator();

Below code is to set the background color of a text box.


Below code is to remove a text box;


From version 0.5.5, we support high level APIs for images. Below codes will create a image and add it to a document with a paragraph as the anchor position.

        Paragraph para = doc.getParagraphByIndex(1, false);
Image image = Image.newImage(para, new URI("file:/c:/image.jpg"));

Below codes can set the properties of image, and even the vertical (or horizontal) alignment.

        image.setTitle("Image title");
image.setDescription("This is a sample image");

If you want to add a hyperlink to your image, you can use the following code:

        image.setHyperlink(new URI(""));

If you want to handle more style settings of image, you can try FrameStyleHandler.

        FrameStyleHandler handler = image.getStyleHandler();

From version 0.5.5, we support high level APIs for span. You can create a span based on a text selection. With span, you can set a different style to this small unit.

        TextNavigation navigation = new TextNavigation("test", doc);
TextSelection sel = (TextSelection) navigation.nextSelection();
Span span = Span.newSpan(sel);
DefaultStyleHandler styleHandler = span.getStyleHandler();
Font font1Base = new Font("Arial", FontStyle.ITALIC, 10, Color.BLACK, TextLinePosition.THROUGH);

The following code is to apply a hyperlink to this span.

        span.applyHyperlink(new URI("ftp://ftpserver"));

Page Break
From version 0.6.5, we support page break feature. You can add page break at the end of text document or after a reference paragraph. It may help you well format your document.

        TextDocument newDoc = TextDocument.newTextDocument();
//add a page break at the end of document. newDoc.addPageBreak();
//add a page break at the end of reference paragraph. Paragraph refParagraph = newDoc.addParagraph("before page break");
From version 0.8, we support to appoint the page style for the page that follows the added page break. You can get a page style by the name and use it as one parameter when adding a page break.

        TextDocument newDoc = TextDocument.newTextDocument();
MasterPage master = (MasterPage) getOrCreateMasterPage(newDoc, "Envelope");
Paragraph refParagraph = newDoc.addParagraph("before page break");
newDoc.addPageBreak(refParagraph, master);
You can also create a customized page style and use it with a page break.

        TextDocument newDoc = TextDocument.newTextDocument();
MasterPage master = (MasterPage) getOrCreateMasterPage(newDoc, "Landscape");
//create a customized page style with specified width, height, margins and other properties. maste.setPageWidth(279.4);
master.setMargins(20, 20, 20, 20);
master.setFootnoteSepProperties(AdjustmentStyle.LEFT, Color.valueOf("#000000"), 1, 1, null, Percent.valueOf("25%"), 0.18);
Paragraph refParagraph = newDoc.addParagraph("before page break");
newDoc.addPageBreak(refParagraph, master);

Table of Content
From version 0.8, we support high level APIs to add table of content (TOC). You can add TOC before/after a reference paragraph by following code. The first parameter is the reference paragraph, the second parameter specifies where to insert the TOC, "true" means before the reference paragraph, "false" means after the reference paragraph.

        TextTableOfContentElement textTableOfContentElement = doc.createDefaultTOC(paragraph1,false);
You can also specify the additional paragraph styles applied on the created TOC. The following codes shows how to generate a TOC before a reference paragraph with customized styles.

        TOCStyle tocstyle = new TOCStyle();
        tocstyle.addStyle("User_20_Index_20_1", 1);
        tocstyle.addStyle("User_20_Index_20_2", 2);
        tocstyle.addStyle("User_20_Index_20_3", 3);
        tocstyle.addStyle("User_20_Index_20_4", 4);
        tocstyle.addStyle("User_20_Index_20_5", 5);
        tocstyle.addStyle("User_20_Index_20_6", 6);
        tocstyle.addStyle("User_20_Index_20_7", 7);
        tocstyle.addStyle("User_20_Index_20_8", 8);
        tocstyle.addStyle("User_20_Index_20_9", 9);
        tocstyle.addStyle("User_20_Index_20_10", 10);
        TextTableOfContentElement textTableOfContentElement = doc.createTOCwithStyle(paragraph1, tocstyle, true);

Powered by the Apache CMS.

Apache "ODF Toolkit" is an effort undergoing incubation at The Apache Software Foundation (ASF), sponsored by the Apache Incubator. Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, communications, and decision making process have stabilized in a manner consistent with other successful ASF projects. While incubation status is not necessarily a reflection of the completeness or stability of the code, it does indicate that the project has yet to be fully endorsed by the ASF.

Copyright © 2011 The Apache Software Foundation Licensed under the Apache License, Version 2.0. Contact Us
Apache and the Apache feather logos are trademarks of The Apache Software Foundation.
Other names appearing on the site may be trademarks of their respective owners.