Simply pass the string of text you need to insert into the document to the DocumentBuilder.Write method. Text formatting is determined by the Font property. This object contains different font attributes (font name, font size, color, and so on).
Some important font attributes are also represented by DocumentBuilder properties to allow you to access them directly. These are boolean properties Font.Bold, Font.Italic, and Font.Underline.
Note that the character formatting you set will apply to all text inserted from the current position in the document onwards.
Example
Inserts formatted text using DocumentBuilder.
[Java]
DocumentBuilder builder = new DocumentBuilder();
// Specify font formatting before adding text.
Font font = builder.getFont();
font.setSize(16);
font.setBold(true);
font.setColor(Color.BLUE);
font.setName("Arial");
font.setUnderline(Underline.DASH);
builder.write("Sample text.");
DocumentBuilder.Writeln inserts a string of text into the document as well but in addition it adds a paragraph break. Current font formatting is also specified by the DocumentBuilder.Font property and current paragraph formatting is determined by the DocumentBuilder.ParagraphFormat property.
Example
Shows how to insert a paragraph into the document.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify font formatting
Font font = builder.getFont();
font.setSize(16);
font.setBold(true);
font.setColor(Color.BLUE);
font.setName("Arial");
font.setUnderline(Underline.DASH);
// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.getParagraphFormat();
paragraphFormat.setFirstLineIndent(8);
paragraphFormat.setAlignment(ParagraphAlignment.JUSTIFY);
paragraphFormat.setKeepTogether(true);
builder.writeln("A whole paragraph.");
The basic algorithm to create a table using DocumentBuilder is simple:
1. Start the table using DocumentBuilder.StartTable.
2. Insert a cell using DocumentBuilder.InsertCell. This automatically starts a new row. If needed, use the DocumentBuilder.CellFormat property to specify cell formatting.
3. Insert cell contents using the DocumentBuilder methods.
4. Repeat steps 2 and 3 until the row is complete.
5. Call DocumentBuilder.EndRow to end the current row. If needed, use DocumentBuilder.RowFormat property to specify row formatting.
6. Repeat steps 2 - 5 until the table is complete.
7. Call DocumentBuilder.EndTable to finish the table building.
The appropriate DocumentBuilder table creation methods are described below.
Calling DocumentBuilder.StartTable is the first step in building a table. It can be also called inside a cell, in which case it starts a nested table. The next method to call is DocumentBuilder.InsertCell.
After you call DocumentBuilder.InsertCell, a new cell is created and any content you add using other methods of the DocumentBuilder class will be added to the current cell. To start a new cell in the same row, call DocumentBuilder.InsertCell again.
Use the DocumentBuilder.CellFormat property to specify cell formatting. It returns a CellFormat object that represents all formatting for a table cell.
Call DocumentBuilder.EndRow to finish the current row. If you call DocumentBuilder.InsertCell immediately after that, then the table continues on a new row.
Use the DocumentBuilder.RowFormat property to specify row formatting. It returns a RowFormat object that represents all formatting for a table row.
Call DocumentBuilder.EndTable to finish the current table. This method should be called only once after DocumentBuilder.EndRow was called. When called, DocumentBuilder.EndTable moves the cursor out of the current cell to a position just after the table.
The following example demonstrates how to build a formatted table that contains 2 rows and 2 columns.
Example
Shows how to build a formatted table that contains 2 rows and 2 columns.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.startTable();
// Insert a cell
builder.insertCell();
// Use fixed column widths.
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
builder.write("This is row 1 cell 1");
// Insert a cell
builder.insertCell();
builder.write("This is row 1 cell 2");
builder.endRow();
// Insert a cell
builder.insertCell();
// Apply new row formatting
builder.getRowFormat().setHeight(100);
builder.getRowFormat().setHeightRule(HeightRule.EXACTLY);
builder.getCellFormat().setOrientation(TextOrientation.UPWARD);
builder.writeln("This is row 2 cell 1");
// Insert a cell
builder.insertCell();
builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD);
builder.writeln("This is row 2 cell 2");
builder.endRow();
builder.endTable();
If you want to explicitly start a new line, paragraph, column, section, or page, call DocumentBuilder.InsertBreak. Pass to this method the type of the break you need to insert that is represented by the BreakType enumeration.
Example
Shows how to insert page breaks into a document.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("This is page 1.");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("This is page 2.");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("This is page 3.");
DocumentBuilder provides several overloads of the DocumentBuilder.InsertImage method that allow you to insert an inline or floating image. If the image is an EMF or WMF metafile, it will be inserted into the document in metafile format. All other images will be stored in PNG format.
The DocumentBuilder.InsertImage method can use images from different sources:
· From a file or URL by passing a string parameter DocumentBuilder.InsertImage(String)
· From a stream by passing a InputStream parameter DocumentBuilder.InsertImage(Stream)
· From a BufferedImage object by passing an Image parameter DocumentBuilder.InsertImage(Image)
· From a byte array by passing a byte array parameter DocumentBuilder.InsertImage(Byte[])
For each of the DocumentBuilder.InsertImage methods listed above, there are further overloads which allow you to insert an image with the following options:
· Inline or floating at a specific position e.g DocumentBuilder.InsertImage(String,RelativeHorizontalPosition, double, RelativeVerticalPosition, double, double, double, WrapType)
· Percentage scale or custom size e.g DocumentBuilder.InsertImage(Stream, double, double)
Furthermore the DocumentBuilder.InsertImage method returns a Shape object that was just created and inserted so you can further modify properties of the Shape.
Pass a single string representing a file that contains the image to DocumentBuilder.InsertImage to insert the image into the document as an inline graphic.
Example
Shows how to insert an inline image at the cursor position into a document.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertImage(getMyDir() + "Watermark.png");
This example inserts a floating image from a file or URL at a specified position and size
Example
Shows how to insert a floating image from a file or URL.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertImage(getMyDir() + "Watermark.png",
RelativeHorizontalPosition.MARGIN,
100,
RelativeVerticalPosition.MARGIN,
100,
200,
100,
WrapType.SQUARE);
To insert a bookmark into the document, you should do the following:
1. Call DocumentBuilder.StartBookmark passing it the desired name of the bookmark.
2. Insert the bookmark text using DocumentBuilder methods.
3. Call DocumentBuilder.EndBookmark passing it the same name that you used with DocumentBuilder.StartBookmark.
Bookmarks can overlap and span any range. To create a valid bookmark you need to call both DocumentBuilder.StartBookmark and DocumentBuilder.EndBookmark with the same bookmark name.
Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.
Example
Shows how to insert a bookmark into a document using a document builder.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startBookmark("FineBookmark");
builder.writeln("This is just a fine bookmark.");
builder.endBookmark("FineBookmark");
Fields in Microsoft Word documents consist of a field code and a field result. The field code is like a formula and the field result is the value that the formula produces. The field code may also contain field switches that are additional instructions to perform a specific action.
You can switch between displaying field codes and results in your document in Microsoft Word using the keyboard shortcut Alt+F9. Field codes appear between curly braces ( { } ).
Use DocumentBuilder.InsertField to create fields in the document. You need to specify a field type, field code and field value. If you are not sure about the particular field code syntax, create the field in Microsoft Word first and switch to see its field code.
Example
Inserts a merge field into a document using DocumentBuilder.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertField("MERGEFIELD MyFieldName \\* MERGEFORMAT");
Form fields are a particular case of Word fields that allows "interaction" with the user. Form fields in Microsoft Word include textbox, combobox and checkbox.
DocumentBuilder provides special methods to insert each type of form field into the document: DocumentBuilder.InsertTextInput, DocumentBuilder.InsertCheckBox, and DocumentBuilder.InsertComboBox. Note that if you specify a name for the form field, then a bookmark is automatically created with the same name.
Call DocumentBuilder.InsertTextInput to insert a textbox into the document.
Example
Shows how to insert a text input form field into a document.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", "Hello", 0);
Call DocumentBuilder.InsertCheckBox to insert a checkbox into the document.
Example
Shows how to insert a checkbox form field into a document.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertCheckBox("CheckBox", true, 0);
Call DocumentBuilder.InsertComboBox to insert a combobox into the document.
Example
Shows how to insert a combobox form field into a document.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
String[] items = {"One", "Two", "Three"};
builder.insertComboBox("DropDown", items, 0);
You can easily insert an HTML string that contains an HTML fragment or whole HTML document into the Word document. Just pass this string to the DocumentBuilder.InsertHtml method. One of the useful implementations of the method is storing an HTML string in a database and inserting it into the document during mail merge to get the formatted content added instead of building it using various methods of the document builder.
Example
Inserts HTML into a document using DocumentBuilder.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertHtml(
"<P align='right'>Paragraph right</P>" +
"<b>Implicit paragraph left</b>" +
"<div align='center'>Div center</div>" +
"<h1 align='left'>Heading 1 left.</h1>");
doc.save(getMyDir() + "DocumentBuilder.InsertHtml Out.doc");
Use DocumentBuilder.InsertHyperlink to insert a hyperlink into the document. This method accepts three parameters: text of the link to be displayed in the document, link destination (URL or a name of a bookmark inside the document), and a boolean parameter that should be true if the URL is a name of a bookmark inside the document.
DocumentBuilder.InsertHyperlink internally calls DocumentBuilder.InsertField to insert a Microsoft Word HYPERLINK field into the document. The HYPERLINK field is created by this method in the following format:
HYPERLINK \l "bookmarkName"
HYPERLINK "http://www.mydomain.com/myurl"
The method always adds apostrophes at the beginning and end of the URL.
Note that you need to specify font formatting for the hyperlink display text explicitly using the Font property.
Example
Inserts a hyperlink into a document using DocumentBuilder.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Please make sure to visit ");
// Specify font formatting for the hyperlink.
builder.getFont().setColor(Color.BLUE);
builder.getFont().setUnderline(Underline.SINGLE);
// Insert the link.
builder.insertHyperlink("Aspose Website", "http://www.aspose.com", false);
// Revert to default formatting.
builder.getFont().clearFormatting();
builder.write(" for more information.");
doc.save(getMyDir() + "DocumentBuilder.InsertHyperlink Out.doc");
You can insert a TOC (table of contents) field into the document at the current position by calling the DocumentBuilder.InsertTableOfContents method.
The DocumentBuilder.InsertTableOfContents method will only insert a TOC field into the document. In order to build the table of contents and display the according page numbers, the both Document.UpdateFields method must be called after the insertion of the field.
Example
Shows how to insert a Table of Contents field into a document.
[Java]
Document doc = new 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");
// The newly inserted table of contents will be initially empty.
// It needs to be populated by updating the fields in the document.
doc.updateFields();