This section describes how to use the DocumentBuilder class to easily generate documents or insert rich content and formatting.
DocumentBuilder is a powerful class that is associated with a Document and allows dynamic document building from scratch or the addition of new elements to an existing document. It provides methods to insert text, paragraphs, lists, tables, images and other contents, specification of font, paragraph, and section formatting, and other things. Using DocumentBuilder is somewhat similar in concept to using the StringBuilder class of the Java Platform.
DocumentBuilder complements classes and methods available in the Aspose.Words Document Object Model by simplifying most common document building tasks, such as inserting text, tables, fields and hyperlinks.
Everything that is possible with DocumentBuilder is also possible when using the classes of the Aspose.Words Document Object Model directly, but using Aspose.Words DOM classes directly usually requires more lines of code than using DocumentBuilder.
DocumentBuilder has an internal cursor that you can navigate to a different location in a document using various DocumentBuilder.MoveToXXX methods such as DocumentBuilder.MoveToDocumentStart and DocumentBuilder.MoveToField.
You can insert text, images, bookmarks, form fields, and other document elements at the cursor position using any of DocumentBuilder.InsertXXX methods such as DocumentBuilder.InsertField, DocumentBuilder.InsertHtml and other similar methods.
Aspose.Words API provides several classes responsible for different document elements’ formatting. Each of the classes encapsulates a number of formatting properties related to a particular document element such as text, paragraph, section, and so on. For example, the Font class represents character formatting properties, the ParagraphFormat class represents paragraph formatting properties etc. The objects of these classes are returned by the corresponding DocumentBuilder properties (that have the same names as the classes) so you can access them and set desired formatting during the document build.
To start, you need to create a DocumentBuilder and associate it with a Document object.
Create a new instance of DocumentBuilder.#ctor(Document) by calling its constructor and pass to it a Document object for attachment to the builder.
Example
Shows how to create a simple document using a document builder.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Hello World!");