Adding content to a document
To explain how the library works, let's create a new empty file and add different types of content to it: heading, paragraphs, lists, tables and page breaks.
As a first step, create the document, instantiating the class CreateDocx:
Now, add the new contents for this docx object, always following the visualization order.
Headings are strings highlighted in the document. To add a heading, call addHeading:
text is the string, level is the heading level and options is the text properties as color, spacing or bold properties, underline, and so on.
For this document insert a text line with color and font size 24:
The method for adding paragraphs is addText:
The first parameter can be a string, an OptionText object or an ArrayList
The second parameter is optional. It defines the properties of the paragraph, like background color, border, alignment and spacing.
Now, add to the document a string with background and text color:
If you prefer to add two or more strings, create a new ArrayList with the text WordFragments to be added. For example:
The "text" option is used for adding the text. The bold font type is enabled in the second paragraph only.
addList is the method for adding lists to a document:
This method includes the following parameters:
- data, ArrayList with the information to add to the list
- styleType, for list types:
- "0", list without styles
- "1", unordered lists
- "2", ordered lists
- a custom list style
- options, for colors and other text properties
Let's add an ordered list of Internet browsers to the document:
To nest lists, just add new ArrayList elements as values. For example:
Including tables is very similar to adding lists, but you must work with nested ArrayList elements to define the text and its properties.
You need to use addTable:
The taleData parameter is an ArrayList which can contain the contents to be added. The other two parameters define the table global properties and particular row properties such as borders, sizes and spans.
To make page or line breaks, use addBreak:
You just need to indicate the type of break, ‘line’ or ‘page’, and the number of breaks to apply.
For example, to make a page break:
For adding a link, use the addLink method:
The options parameter defines the link destination and the text properties.
Here's a simple example:
This method links the text to the URL www.javadocx.com with a color and no underline.