Document Builder Overview
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, checkbox, ole object, 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 .NET Framework.
DocumentBuilder complements classes and methods available in the Aspose.Words Document Object Model by simplifying most common document building tasks, such as inserting text, checkbox, ole object, 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 require 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, checkbox, ole object, 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 the 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 by calling its constructor and pass to it a Document object for attachment to the builder. To insert a text, simply pass the string of text you need to insert into the document to the DocumentBuilder.Write method. Below example shows how to create a simple document using a document builder.
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. Below example Inserts formatted text using DocumentBuilder: