Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
The DocumentBuilder is used to modify documents. This article explains and describes how to perform a number of tasks.
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.getBold, Font.getItalic, and Font.getUnderline.
The following code example Inserts formatted text using DocumentBuilder.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Font font = builder.getFont(); | |
font.setSize(16); | |
font.setColor(Color.blue); | |
font.setBold(true); | |
font.setName("Algerian"); | |
font.setUnderline(Underline.DOUBLE); | |
builder.write("aspose......... aspose_words_java"); |
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.getFont property and current paragraph formatting is determined by the DocumentBuilder.getParagraphFormat property.
The following code example shows how to insert a paragraph into the document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Font font = builder.getFont(); | |
font.setSize(16); | |
font.setColor(Color.DARK_GRAY); | |
font.setBold(true); | |
font.setName("Algerian"); | |
font.setUnderline(2); | |
ParagraphFormat paragraphFormat = builder.getParagraphFormat(); | |
paragraphFormat.setFirstLineIndent(12); | |
paragraphFormat.setAlignment(1); | |
paragraphFormat.setKeepTogether(true); | |
builder.write("This is a sample Paragraph"); | |
doc.save(dataDir + "InsertParagraph_out.doc"); |
The basic algorithm to create a table using DocumentBuilder
is simple:
DocumentBuilder
methods.Calling DocumentBuilder.startTable is the first step in building a table. It can be also called inside a cell, in this 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.getCellFormat property to specify cell formatting. It returns a getCellFormat 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.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderBuildTable.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Table table = builder.startTable(); | |
builder.insertCell(); | |
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); | |
builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); | |
builder.write("This is Row 1 Cell 1"); | |
builder.insertCell(); | |
builder.write("This is Row 1 Cell 2"); | |
builder.endRow(); | |
builder.getRowFormat().setHeight(100); | |
builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); | |
builder.getCellFormat().setOrientation(TextOrientation.UPWARD); | |
builder.write("This is Row 2 Cell 1"); | |
builder.insertCell(); | |
builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); | |
builder.write("This is Row 2 Cell 2"); | |
builder.endRow(); | |
builder.endTable(); | |
doc.save(dataDir + "output.doc"); |
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.
The following code example shows how to insert page breaks into a document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertBreak.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("This is Page 1"); | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
builder.write("This is Page 2"); | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
builder.write("This is Page 3"); | |
doc.save(dataDir + "output.doc"); |
DocumentBuilder provides several overloads of the DocumentBuilder.insertImage method that allows 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:
URL
by passing a string parameterStream
parameterFor each of the DocumentBuilder.insertImage methods, there are further overloads which allow you to insert an image with the following options:
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. The following code example shows how to insert an inline image at the cursor position into a document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertInlineImage.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertImage(dataDir + "test.jpg"); | |
doc.save(dataDir + "output.doc"); |
This example inserts a floating image from a file or URL
at a specified position and size.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertFloatingImage.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertImage(dataDir + "test.jpg", | |
RelativeHorizontalPosition.MARGIN, | |
100, | |
RelativeVerticalPosition.MARGIN, | |
100, | |
200, | |
100, | |
WrapType.SQUARE); | |
doc.save(dataDir + "output.doc"); |
To insert a bookmark into the document, you should do the following:
DocumentBuilder
methods.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.
The following code example shows how to insert a bookmark into a document using a document builder.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertBookmark.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.startBookmark("FineBookMark"); | |
builder.write("This is just a fine bookmark."); | |
builder.endBookmark("FineBookmark"); | |
doc.save(dataDir + "output.doc");// |
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.
The following code example inserts a merge field into a document using DocumentBuilder.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertField.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.getFont().setLocaleId(1031); | |
builder.insertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\""); | |
builder.write(" - "); | |
builder.insertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\""); | |
doc.save(dataDir + "output.doc"); |
Form
FieldForm 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.
DocumentBuilder.insertTextInput to insert a textbox into the document. The following code example shows how to insert a text input form field into a document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertTextInputFormField.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", "Hello", 0); | |
doc.save(dataDir + "output.doc"); |
CheckBox
Call DocumentBuilder.insertCheckBox to insert a checkbox into the document. The following code example shows how to insert a checkbox form field into a document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertCheckBoxFormField.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertCheckBox("CheckBox", true, true, 0); | |
doc.save(dataDir + "output.doc"); |
Call DocumentBuilder.insertComboBox to insert a combo box into the document. The following code example shows how to insert a combo box form field into a document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertComboBoxFormField.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
String[] items = {"One", "Two", "Three"}; | |
builder.insertComboBox("DropDown", items, 0); | |
doc.save(dataDir + "output.doc"); |
Customers can specify Locale at field level now and can achieve better control. Locale Ids can be associated with each field inside the DocumentBuilder. The examples below illustrate how to make use of this option.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
DocumentBuilder builder = new DocumentBuilder(); | |
Field field = builder.insertField(FieldType.FIELD_DATE, true); | |
field.setLocaleId(1049); | |
builder.getDocument().save(getArtifactsDir() + "WorkingWithFields.SpecifylocaleAtFieldlevel.docx"); |
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. The following code example shows inserts HTML into a document using DocumentBuilder.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertHtml.class); | |
// Open the document. | |
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(dataDir + "output.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. 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. The following code example inserts a hyperlink into a document using DocumentBuilder.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("Please make sure to visit "); | |
builder.getFont().setColor(Color.BLUE); | |
builder.getFont().setUnderline(Underline.SINGLE); | |
builder.insertHyperlink("Aspose Website", "http://www.aspose.com", false); | |
builder.getFont().clearFormatting(); | |
builder.write(" for more information."); | |
doc.save(getArtifactsDir() + "AddContentUsingDocumentBuilder.InsertHyperlink.docx"); |
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 them according to page numbers, the both Document.UpdateFieldsmethod must be called after the insertion of the field. The following code example shows how to insert a Table of Contents field into a document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertTableOfContents.class); | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u"); | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1); | |
builder.writeln("Heading 1"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2); | |
builder.writeln("Heading 1.1"); | |
builder.writeln("Heading 1.2"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1); | |
builder.writeln("Heading 2"); | |
builder.writeln("Heading 3"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2); | |
builder.writeln("Heading 3.1"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_3); | |
builder.writeln("Heading 3.1.1"); | |
builder.writeln("Heading 3.1.2"); | |
builder.writeln("Heading 3.1.3"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2); | |
builder.writeln("Heading 3.2"); | |
builder.writeln("Heading 3.3"); | |
doc.updateFields(); | |
doc.save(dataDir + "output.doc"); |
If you want Ole Object call DocumentBuilder.insertOleObjectAsIcon.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertOleObject("http://www.aspose.com", "htmlfile", true, true, null); | |
doc.save(getArtifactsDir() + "WorkingWithOleObjectsAndActiveX.InsertOleObject.docx"); |
OLE package is a legacy and “undocumented” way to store embedded objects if the OLE handler is unknown. Early Windows versions such as Windows 3.1, 95 and 98 had Packager.exe application which could be used to embed any type of data into the document. Now, this application is excluded from Windows but MS Word and other applications still use it to embed data if the OLE handler is missing or unknown. OlePackage class allows accessing OLE Package properties.The following code example shows how to set the file name, extension and display name for OLE Package.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
byte[] bs = FileUtils.readFileToByteArray(new File(getMyDir() + "Zip file.zip")); | |
try (ByteArrayInputStream stream = new ByteArrayInputStream(bs)) | |
{ | |
Shape shape = builder.insertOleObject(stream, "Package", true, null); | |
OlePackage olePackage = shape.getOleFormat().getOlePackage(); | |
olePackage.setFileName("filename.zip"); | |
olePackage.setDisplayName("displayname.zip"); | |
doc.save(getArtifactsDir() + "WorkingWithOleObjectsAndActiveX.InsertOleObjectWithOlePackage.docx"); | |
} |
The following code example demonstrates how to get OLE Object raw data using OleFormat.GetRawData
() method.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Shape oleShape = (Shape) doc.getChild(NodeType.SHAPE, 0, true); | |
byte[] oleRawData = oleShape.getOleFormat().getRawData(); |
The following code example shows how to insert horizontal rule shape into a document using DocumentBuilder.InsertHorizontalRule
method.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Initialize document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.writeln("Insert a horizontal rule shape into the document."); | |
builder.insertHorizontalRule(); | |
dataDir = dataDir + "DocumentBuilder.InsertHorizontalRule_out.doc"; | |
doc.save(dataDir); |
You can insert an inline shape with a specified type and size and a free-floating shape with the specified position, size and text wrap type into a document using DocumentBuilder.InsertShape
method. The DocumentBuilder.InsertShape
method allows to insert DML shape into the document model. The document must be saved in the format, which support DML shapes, otherwise such nodes will be converted to VML shape, while document saving. The following code example shows how to insert these types of shapes into the document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
//Free-floating shape insertion. | |
Shape shape = builder.insertShape(ShapeType.TEXT_BOX, | |
RelativeHorizontalPosition.PAGE, 100, | |
RelativeVerticalPosition.PAGE, 100, | |
50, 50, | |
WrapType.NONE); | |
shape.setRotation(30.0); | |
builder.writeln(); | |
//Inline shape insertion. | |
shape = builder.insertShape(ShapeType.TEXT_BOX, 50, 50); | |
shape.setRotation(30.0); | |
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.DOCX); | |
// "Strict" or "Transitional" compliance allows to save shape as DML. | |
so.setCompliance(OoxmlCompliance.ISO_29500_2008_TRANSITIONAL); | |
dataDir = dataDir + "Shape_InsertShapeUsingDocumentBuilder_out.docx"; | |
// Save the document to disk. | |
doc.save(dataDir, so); |
You can create a snip corner rectangle using Aspose.Words. The shape types are SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, and DiagonalCornersRounded. The DML shape is created using DocumentBuilder.InsertShape
method with these shape types. These types cannot be used to create VML shapes. Attempt to create a shape by using the public constructor of the “Shape” class raises the “NotSupportedException” exception. The following code example shows how to insert these types of shapes into the document.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Shape shape = builder.insertShape(ShapeType.TOP_CORNERS_SNIPPED, 50, 50); | |
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.DOCX); | |
so.setCompliance(OoxmlCompliance.ISO_29500_2008_TRANSITIONAL); | |
dataDir = dataDir + "AddCornersSnipped_out.docx"; | |
//Save the document to disk. | |
doc.save(dataDir, so); |
You can use LoadOptions.ConvertShapeToOfficeMath
property to convert the shapes with EquationXML to Office Math objects. The default value of this property corresponds to MS Word behavior i.e. shapes with equation XML are not converted to Office math objects.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
LoadOptions lo = new LoadOptions(); | |
lo.setConvertShapeToOfficeMath(true); | |
// Specify load option to use previous default behaviour i.e. convert math | |
// shapes to office math ojects on loading stage. | |
Document doc = new Document(dataDir + "OfficeMath.docx", lo); | |
// Save the document into DOCX | |
doc.save(dataDir + "ConvertShapeToOfficeMath_out.docx", SaveFormat.DOCX); |
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.