java.lang.Objectcom.aspose.words.DocumentBuilder
public class DocumentBuilder
DocumentBuilder makes the process of building a Document easier.
Document is a composite object consisting of a tree of nodes and while inserting content
nodes directly into the tree is possible, it requires good understanding of the tree structure.
DocumentBuilder is a "facade" for the complex structure of Document and allows
to insert content and formatting quickly and easily. Create a DocumentBuilder and associate it with a The DocumentBuilder has an internal cursor where the text will be inserted
when you call Use the Use the Use the Use the Note that Font, ParagraphFormat and PageSetup properties are updated whenever
you navigate to a different place in the document to reflect formatting properties available at the new location. Example: Example: Example:
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// We call this method to start building the table
builder.startTable();
builder.insertCell();
builder.write("Row 1, Cell 1 Content.");
// Build the second cell
builder.insertCell();
builder.write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row
builder.endRow();
// Build the first cell of the second row
builder.insertCell();
builder.write("Row 2, Cell 1 Content.");
// Build the second cell.
builder.insertCell();
builder.write("Row 2, Cell 2 Content.");
builder.endRow();
// Signal that we have finished building the table
builder.endTable();
// Save the document to disk
doc.save(getArtifactsDir() + "DocumentBuilder.CreateSimpleTable.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify that we want headers and footers different for first, even and odd pages
builder.getPageSetup().setDifferentFirstPageHeaderFooter(true);
builder.getPageSetup().setOddAndEvenPagesHeaderFooter(true);
// Create the headers
builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST);
builder.write("Header for the first page");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_EVEN);
builder.write("Header for even pages");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.write("Header for all other pages");
// Create three pages in the document
builder.moveToSection(0);
builder.writeln("Page1");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("Page2");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("Page3");
doc.save(getArtifactsDir() + "DocumentBuilder.HeadersAndFooters.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Start building a table
builder.startTable();
// Set the appropriate paragraph, cell, and row formatting. The formatting properties are preserved
// until they are explicitly modified so there's no need to set them for each row or cell
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
builder.getCellFormat().clearFormatting();
builder.getCellFormat().setWidth(150.0);
builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN);
builder.getCellFormat().setWrapText(false);
builder.getCellFormat().setFitText(true);
builder.getRowFormat().clearFormatting();
builder.getRowFormat().setHeightRule(HeightRule.EXACTLY);
builder.getRowFormat().setHeight(50.0);
builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D);
builder.getRowFormat().getBorders().setColor(Color.ORANGE);
builder.insertCell();
builder.write("Row 1, Col 1");
builder.insertCell();
builder.write("Row 1, Col 2");
builder.endRow();
// Remove the shading (clear background)
builder.getCellFormat().getShading().clearFormatting();
builder.insertCell();
builder.write("Row 2, Col 1");
builder.insertCell();
builder.write("Row 2, Col 2");
builder.endRow();
builder.insertCell();
// Make the row height bigger so that a vertically oriented text could fit into cells
builder.getRowFormat().setHeight(150.0);
builder.getCellFormat().setOrientation(TextOrientation.UPWARD);
builder.write("Row 3, Col 1");
builder.insertCell();
builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD);
builder.write("Row 3, Col 2");
builder.endRow();
builder.endTable();
doc.save(getArtifactsDir() + "DocumentBuilder.InsertTable.docx");
Constructor Summary |
---|
DocumentBuilder()
Initializes a new instance of this class. |
DocumentBuilder(Document doc)
Initializes a new instance of this class. |
Property Getters/Setters Summary | ||
---|---|---|
boolean | getBold() | |
void | setBold(boolean value) | |
True if the font is formatted as bold. | ||
CellFormat | getCellFormat() | |
Returns an object that represents current table cell formatting properties. | ||
Node | getCurrentNode() | |
Gets the node that is currently selected in this DocumentBuilder. | ||
Paragraph | getCurrentParagraph() | |
Gets the paragraph that is currently selected in this DocumentBuilder. | ||
Section | getCurrentSection() | |
Gets the section that is currently selected in this DocumentBuilder. | ||
Story | getCurrentStory() | |
Gets the story that is currently selected in this DocumentBuilder. | ||
Document | getDocument() | |
void | setDocument(Document value) | |
Gets or sets the |
||
Font | getFont() | |
Returns an object that represents current font formatting properties. | ||
boolean | isAtEndOfParagraph() | |
Returns true if the cursor is at the end of the current paragraph. | ||
boolean | isAtStartOfParagraph() | |
Returns true if the cursor is at the beginning of the current paragraph (no text before the cursor). | ||
boolean | getItalic() | |
void | setItalic(boolean value) | |
True if the font is formatted as italic. | ||
ListFormat | getListFormat() | |
Returns an object that represents current list formatting properties. | ||
PageSetup | getPageSetup() | |
Returns an object that represents current page setup and section properties. | ||
ParagraphFormat | getParagraphFormat() | |
Returns an object that represents current paragraph formatting properties. | ||
RowFormat | getRowFormat() | |
Returns an object that represents current table row formatting properties. | ||
int | getUnderline() | |
void | setUnderline(int value) | |
Gets/sets underline type for the current font. The value of the property is Underline integer constant. |
Method Summary | ||
---|---|---|
Row | deleteRow(int tableIndex, int rowIndex) | |
Deletes a row from a table. | ||
BookmarkEnd | endBookmark(java.lang.String bookmarkName) | |
Marks the current position in the document as a bookmark end. | ||
EditableRangeEnd | endEditableRange() | |
Marks the current position in the document as an editable range end. | ||
EditableRangeEnd | endEditableRange(EditableRangeStart start) | |
Marks the current position in the document as an editable range end. | ||
Row | endRow() | |
Ends a table row in the document. | ||
Table | endTable() | |
Ends a table in the document. | ||
void | insertBreak(int breakType) | |
Inserts a break of the specified type into the document. | ||
Cell | insertCell() | |
Inserts a table cell into the document. | ||
Shape | insertChart(int chartType, double width, double height) | |
Inserts an chart object into the document and scales it to the specified size. | ||
Shape | insertChart(int chartType, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) | |
Inserts an chart object into the document and scales it to the specified size. | ||
FormField | insertCheckBox(java.lang.String name, boolean defaultValue, boolean checkedValue, int size) | |
Inserts a checkbox form field at the current position. | ||
FormField | insertCheckBox(java.lang.String name, boolean checkedValue, int size) | |
Inserts a checkbox form field at the current position. | ||
FormField | insertComboBox(java.lang.String name, java.lang.String[] items, int selectedIndex) | |
Inserts a combobox form field at the current position. | ||
Node | insertDocument(Document srcDoc, int importFormatMode) | |
Inserts a document at the cursor position. | ||
Node | insertDocument(Document srcDoc, int importFormatMode, ImportFormatOptions importFormatOptions) | |
Inserts a document at the cursor position. | ||
Field | insertField(int fieldType, boolean updateField) | |
Inserts a Word field into a document and optionally updates the field result. | ||
Field | insertField(java.lang.String fieldCode) | |
Inserts a Word field into a document and updates the field result. | ||
Field | insertField(java.lang.String fieldCode, java.lang.String fieldValue) | |
Inserts a Word field into a document without updating the field result. | ||
Footnote | insertFootnote(int footnoteType, java.lang.String footnoteText) | |
Inserts a footnote or endnote into the document. | ||
Footnote | insertFootnote(int footnoteType, java.lang.String footnoteText, java.lang.String referenceMark) | |
Inserts a footnote or endnote into the document. | ||
Shape | insertHorizontalRule() | |
Inserts a horizontal rule shape into the document. | ||
void | insertHtml(java.lang.String html) | |
Inserts an HTML string into the document. | ||
void | insertHtml(java.lang.String html, boolean useBuilderFormatting) | |
Inserts an HTML string into the document. | ||
Field | insertHyperlink(java.lang.String displayText, java.lang.String urlOrBookmark, boolean isBookmark) | |
Inserts a hyperlink into the document. | ||
Shape | insertImage(byte[] imageBytes) | |
Inserts an image from a byte array into the document. The image is inserted inline and at 100% scale. | ||
Shape | insertImage(byte[] imageBytes, double width, double height) | |
Inserts an inline image from a byte array into the document and scales it to the specified size. | ||
Shape | insertImage(byte[] imageBytes, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) | |
Inserts an image from a byte array at the specified position and size. | ||
Shape | insertImage(java.awt.image.BufferedImage image) | |
Inserts an image from a |
||
Shape | insertImage(java.awt.image.BufferedImage image, double width, double height) | |
Inserts an inline image from a |
||
Shape | insertImage(java.awt.image.BufferedImage image, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) | |
Inserts an image from a |
||
Shape | insertImage(java.io.InputStream stream) | |
Inserts an image from a stream into the document. The image is inserted inline and at 100% scale. | ||
Shape | insertImage(java.io.InputStream stream, double width, double height) | |
Inserts an inline image from a stream into the document and scales it to the specified size. | ||
Shape | insertImage(java.io.InputStream stream, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) | |
Inserts an image from a stream at the specified position and size. | ||
Shape | insertImage(java.lang.String fileName) | |
Inserts an image from a file or URL into the document. The image is inserted inline and at 100% scale. | ||
Shape | insertImage(java.lang.String fileName, double width, double height) | |
Inserts an inline image from a file or URL into the document and scales it to the specified size. | ||
Shape | insertImage(java.lang.String fileName, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) | |
Inserts an image from a file or URL at the specified position and size. | ||
void | insertNode(Node node) | |
Inserts a text level node inside the current paragraph before the cursor. | ||
Shape | insertOleObject(java.io.InputStream stream, java.lang.String progId, boolean asIcon, java.awt.image.BufferedImage presentation) | |
Inserts an embedded OLE object from a stream into the document. | ||
Shape | insertOleObject(java.lang.String fileName, boolean isLinked, boolean asIcon, java.awt.image.BufferedImage presentation) | |
Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using file extension. | ||
Shape | insertOleObject(java.lang.String fileName, java.lang.String progId, boolean isLinked, boolean asIcon, java.awt.image.BufferedImage presentation) | |
Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using given progID parameter. | ||
Shape | insertOleObjectAsIcon(java.lang.String fileName, boolean isLinked, java.lang.String iconFile, java.lang.String iconCaption) | |
Inserts an embedded or linked OLE object as icon into the document. Allows to specify icon file and caption. Detects OLE object type using file extension. | ||
Shape | insertOnlineVideo(java.lang.String videoUrl, double width, double height) | |
Inserts an online video object into the document and scales it to the specified size. | ||
Shape | insertOnlineVideo(java.lang.String videoUrl, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) | |
Inserts an online video object into the document and scales it to the specified size. | ||
Shape | insertOnlineVideo(java.lang.String videoUrl, java.lang.String videoEmbedCode, byte[] thumbnailImageBytes, double width, double height) | |
Inserts an online video object into the document and scales it to the specified size. | ||
Shape | insertOnlineVideo(java.lang.String videoUrl, java.lang.String videoEmbedCode, byte[] thumbnailImageBytes, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) | |
Inserts an online video object into the document and scales it to the specified size. | ||
Paragraph | insertParagraph() | |
Inserts a paragraph break into the document. | ||
Shape | insertShape(int shapeType, double width, double height) | |
Inserts inline shape with specified type and size. | ||
Shape | insertShape(int shapeType, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) | |
Inserts free-floating shape with specified position, size and text wrap type. | ||
Shape | insertSignatureLine(SignatureLineOptions signatureLineOptions) | |
Inserts a signature line at the current position. | ||
Shape | insertSignatureLine(SignatureLineOptions signatureLineOptions, int horzPos, double left, int vertPos, double top, int wrapType) | |
Inserts a signature line at the specified position. | ||
void | insertStyleSeparator() | |
Inserts style separator into the document. | ||
Field | insertTableOfContents(java.lang.String switches) | |
Inserts a TOC (table of contents) field into the document. | ||
FormField | insertTextInput(java.lang.String name, int type, java.lang.String format, java.lang.String fieldValue, int maxLength) | |
Inserts a text form field at the current position. | ||
void | moveTo(Node node) | |
Moves the cursor to an inline node or to the end of a paragraph. | ||
boolean | moveToBookmark(java.lang.String bookmarkName) | |
Moves the cursor to a bookmark. | ||
boolean | moveToBookmark(java.lang.String bookmarkName, boolean isStart, boolean isAfter) | |
Moves the cursor to a bookmark with greater precision. | ||
void | moveToCell(int tableIndex, int rowIndex, int columnIndex, int characterIndex) | |
Moves the cursor to a table cell in the current section. | ||
void | moveToDocumentEnd() | |
Moves the cursor to the end of the document. | ||
void | moveToDocumentStart() | |
Moves the cursor to the beginning of the document. | ||
void | moveToField(Field field, boolean isAfter) | |
Moves the cursor to a field in the document. | ||
void | moveToHeaderFooter(int headerFooterType) | |
Moves the cursor to the beginning of a header or footer in the current section. | ||
boolean | moveToMergeField(java.lang.String fieldName) | |
Moves the cursor to a position just beyond the specified merge field and removes the merge field. | ||
boolean | moveToMergeField(java.lang.String fieldName, boolean isAfter, boolean isDeleteField) | |
Moves the merge field to the specified merge field. | ||
void | moveToParagraph(int paragraphIndex, int characterIndex) | |
Moves the cursor to a paragraph in the current section. | ||
void | moveToSection(int sectionIndex) | |
Moves the cursor to the beginning of the body in a specified section. | ||
void | popFont() | |
Retrieves character formatting previously saved on the stack. | ||
void | pushFont() | |
Saves current character formatting onto the stack. | ||
BookmarkStart | startBookmark(java.lang.String bookmarkName) | |
Marks the current position in the document as a bookmark start. | ||
EditableRangeStart | startEditableRange() | |
Marks the current position in the document as an editable range start. | ||
Table | startTable() | |
Starts a table in the document. | ||
void | write(java.lang.String text) | |
Inserts a string into the document at the current insert position. | ||
void | writeln() | |
Inserts a paragraph break into the document. | ||
void | writeln(java.lang.String text) | |
Inserts a string and a paragraph break into the document. |
Constructor Detail |
---|
public DocumentBuilder() throws java.lang.Exception
Example:
Inserts formatted text using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Specify font formatting before adding text Font font = builder.getFont(); font.setSize(16); font.setBold(true); font.setColor(Color.BLUE); font.setName("Courier New"); font.setUnderline(Underline.DASH); builder.write("Hello world!");
public DocumentBuilder(Document doc)
doc
- The Document object to attach to.Example:
Shows how to insert a Table of contents (TOC) into a document using heading styles as entries.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table of contents at the beginning of the document, // and set it to pick up paragraphs with headings of levels 1 to 3 and entries to act like hyperlinks builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u"); // Start the actual document content on the second page builder.insertBreak(BreakType.PAGE_BREAK); // Build a document with complex structure by applying different heading styles thus creating TOC entries // The heading levels we use below will affect the list levels in which these items will appear in the TOC, // and only levels 1-3 will be picked up by our TOC due to its settings 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"); // Call the method below to update the TOC and save doc.updateFields(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertToc.docx");
Example:
Shows how to create headers and footers in a document using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Specify that we want headers and footers different for first, even and odd pages builder.getPageSetup().setDifferentFirstPageHeaderFooter(true); builder.getPageSetup().setOddAndEvenPagesHeaderFooter(true); // Create the headers builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST); builder.write("Header for the first page"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_EVEN); builder.write("Header for even pages"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); builder.write("Header for all other pages"); // Create three pages in the document builder.moveToSection(0); builder.writeln("Page1"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page2"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page3"); doc.save(getArtifactsDir() + "DocumentBuilder.HeadersAndFooters.docx");
Property Getters/Setters Detail |
---|
getBold/setBold | |
public boolean getBold() / public void setBold(boolean value) |
Example:
Shows how to fill MERGEFIELDs with data with a DocumentBuilder and without a mail merge.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert some MERGEFIELDS, which accept data from columns of the same name in a data source during a mail merge builder.insertField(" MERGEFIELD Chairman "); builder.insertField(" MERGEFIELD ChiefFinancialOfficer "); builder.insertField(" MERGEFIELD ChiefTechnologyOfficer "); // They can also be filled in manually like this builder.moveToMergeField("Chairman"); builder.setBold(true); builder.writeln("John Doe"); builder.moveToMergeField("ChiefFinancialOfficer"); builder.setItalic(true); builder.writeln("Jane Doe"); builder.moveToMergeField("ChiefTechnologyOfficer"); builder.setItalic(true); builder.writeln("John Bloggs"); doc.save(getArtifactsDir() + "DocumentBuilder.FillMergeFields.docx");
getCellFormat | |
public CellFormat getCellFormat() |
Example:
Shows how to create a table that contains a single formatted cell.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.startTable(); builder.insertCell(); // Set the cell formatting CellFormat cellFormat = builder.getCellFormat(); cellFormat.setWidth(250.0); cellFormat.setLeftPadding(30.0); cellFormat.setRightPadding(30.0); cellFormat.setTopPadding(30.0); cellFormat.setBottomPadding(30.0); builder.write("Formatted cell"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.DocumentBuilderSetCellFormatting.docx");
Example:
Shows how to build a formatted table that contains 2 rows and 2 columns.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Insert a cell builder.insertCell(); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.write("This is row 1 cell 1"); // Use fixed column widths table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); // 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.0); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("This is row 2 cell 1"); // Insert a cell builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("This is row 2 cell 2"); builder.endRow(); builder.endTable();
Example:
Shows how to build a nice bordered table.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start building a table builder.startTable(); // Set the appropriate paragraph, cell, and row formatting. The formatting properties are preserved // until they are explicitly modified so there's no need to set them for each row or cell builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getCellFormat().clearFormatting(); builder.getCellFormat().setWidth(150.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN); builder.getCellFormat().setWrapText(false); builder.getCellFormat().setFitText(true); builder.getRowFormat().clearFormatting(); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getRowFormat().setHeight(50.0); builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D); builder.getRowFormat().getBorders().setColor(Color.ORANGE); builder.insertCell(); builder.write("Row 1, Col 1"); builder.insertCell(); builder.write("Row 1, Col 2"); builder.endRow(); // Remove the shading (clear background) builder.getCellFormat().getShading().clearFormatting(); builder.insertCell(); builder.write("Row 2, Col 1"); builder.insertCell(); builder.write("Row 2, Col 2"); builder.endRow(); builder.insertCell(); // Make the row height bigger so that a vertically oriented text could fit into cells builder.getRowFormat().setHeight(150.0); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("Row 3, Col 1"); builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("Row 3, Col 2"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertTable.docx");
getCurrentNode | |
public Node getCurrentNode() |
CurrentNode is a cursor of DocumentBuilder and points to a Node that is a direct child of a Paragraph. Any insert operations you perform using DocumentBuilder will insert before the CurrentNode.
When the current paragraph is empty or the cursor is positioned just before the end of the paragraph, CurrentNode returns null.
Example:
Shows how to move a DocumentBuilder to different nodes in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start a bookmark and add content to it using a DocumentBuilder builder.startBookmark("MyBookmark"); builder.writeln("Bookmark contents."); builder.endBookmark("MyBookmark"); // The node that the DocumentBuilder is currently at is past the boundaries of the bookmark Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild()); // If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this builder.moveToBookmark("MyBookmark"); // Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild()); // We can move the builder to an individual node, // which in this case will be the first node of the first paragraph, like this builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0)); Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType()); Assert.assertTrue(builder.isAtStartOfParagraph()); // A shorter way of moving the very start/end of a document is with these methods builder.moveToDocumentEnd(); Assert.assertTrue(builder.isAtEndOfParagraph()); builder.moveToDocumentStart(); Assert.assertTrue(builder.isAtStartOfParagraph());
getCurrentParagraph | |
public Paragraph getCurrentParagraph() |
Example:
Shows how to move a DocumentBuilder to different nodes in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start a bookmark and add content to it using a DocumentBuilder builder.startBookmark("MyBookmark"); builder.writeln("Bookmark contents."); builder.endBookmark("MyBookmark"); // The node that the DocumentBuilder is currently at is past the boundaries of the bookmark Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild()); // If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this builder.moveToBookmark("MyBookmark"); // Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild()); // We can move the builder to an individual node, // which in this case will be the first node of the first paragraph, like this builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0)); Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType()); Assert.assertTrue(builder.isAtStartOfParagraph()); // A shorter way of moving the very start/end of a document is with these methods builder.moveToDocumentEnd(); Assert.assertTrue(builder.isAtEndOfParagraph()); builder.moveToDocumentStart(); Assert.assertTrue(builder.isAtStartOfParagraph());
getCurrentSection | |
public Section getCurrentSection() |
Example:
Shows how to insert a floating image and specify its position and size.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // By default, the image is inline Shape shape = builder.insertImage(getImageDir() + "Logo.jpg"); // Make the image float, put it behind text and center on the page shape.setWrapType(WrapType.NONE); // Make position relative to the page shape.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); shape.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); // Set the shape's coordinates, from the top left corner of the page shape.setLeft(100.0); shape.setTop(80.0); // Set the shape's height shape.setHeight(125.0); // The width will be scaled to the height and the dimensions of the real image Assert.assertEquals(shape.getWidth(), 125.0); // The Bottom and Right members contain the locations of the bottom and right edges of the image Assert.assertEquals(shape.getBottom(), shape.getTop() + shape.getHeight()); Assert.assertEquals(shape.getRight(), shape.getLeft() + shape.getWidth()); doc.save(getArtifactsDir() + "Image.CreateFloatingPositionSize.docx");
getCurrentStory | |
public Story getCurrentStory() |
Example:
Shows how to work with a document builder's current story.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // A Story is a type of node that have child Paragraph nodes, such as a Body, // which would usually be a parent node to a DocumentBuilder's current paragraph Assert.assertEquals(builder.getCurrentStory(), doc.getFirstSection().getBody()); Assert.assertEquals(builder.getCurrentStory(), builder.getCurrentParagraph().getParentNode()); Assert.assertEquals(StoryType.MAIN_TEXT, builder.getCurrentStory().getStoryType()); builder.getCurrentStory().appendParagraph("Text added to current Story."); // A Story can contain tables too Table table = builder.startTable(); builder.insertCell(); builder.write("Row 1 cell 1"); builder.insertCell(); builder.write("Row 1 cell 2"); builder.endTable(); // The table we just made is automatically placed in the story Assert.assertTrue(builder.getCurrentStory().getTables().contains(table));
getDocument/setDocument | |
public Document getDocument() / public void setDocument(Document value) |
Example:
Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Modify the first section in the document builder.getPageSetup().setOrientation(Orientation.LANDSCAPE); builder.getPageSetup().setVerticalAlignment(PageVerticalAlignment.CENTER); builder.writeln("Section 1, landscape oriented and text vertically centered."); // Start a new section and reset its formatting to defaults builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE); builder.getPageSetup().clearFormatting(); builder.writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment."); doc.save(getArtifactsDir() + "PageSetup.ClearFormatting.docx");
getFont | |
public Font getFont() |
Use Font to access and modify font formatting properties.
Specify font formatting before inserting text.
Example:
Shows how to insert a string surrounded by a border into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.getFont().getBorder().setColor(Color.GREEN); builder.getFont().getBorder().setLineWidth(2.5); builder.getFont().getBorder().setLineStyle(LineStyle.DASH_DOT_STROKER); builder.write("Text surrounded by green border."); doc.save(getArtifactsDir() + "Border.FontBorder.docx");
Example:
Shows how to create a formatted table using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Make the header row builder.insertCell(); // Set the left indent for the table. Table wide formatting must be applied after // at least one row is present in the table table.setLeftIndent(20.0); // Set height and define the height rule for the header row builder.getRowFormat().setHeight(40.0); builder.getRowFormat().setHeightRule(HeightRule.AT_LEAST); // Some special features for the header row builder.getCellFormat().getShading().setBackgroundPatternColor(new Color(198, 217, 241)); builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getFont().setSize(16); builder.getFont().setName("Arial"); builder.getFont().setBold(true); builder.getCellFormat().setWidth(100.0); builder.write("Header Row,\n Cell 1"); // We don't need to specify the width of this cell because it's inherited from the previous cell builder.insertCell(); builder.write("Header Row,\n Cell 2"); builder.insertCell(); builder.getCellFormat().setWidth(200.0); builder.write("Header Row,\n Cell 3"); builder.endRow(); // Set features for the other rows and cells builder.getCellFormat().getShading().setBackgroundPatternColor(Color.WHITE); builder.getCellFormat().setWidth(100.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); // Reset height and define a different height rule for table body builder.getRowFormat().setHeight(30.0); builder.getRowFormat().setHeightRule(HeightRule.AUTO); builder.insertCell(); // Reset font formatting builder.getFont().setSize(12); builder.getFont().setBold(false); // Build the other cells builder.write("Row 1, Cell 1 Content"); builder.insertCell(); builder.write("Row 1, Cell 2 Content"); builder.insertCell(); builder.getCellFormat().setWidth(200.0); builder.write("Row 1, Cell 3 Content"); builder.endRow(); builder.insertCell(); builder.getCellFormat().setWidth(100.0); builder.write("Row 2, Cell 1 Content"); builder.insertCell(); builder.write("Row 2, Cell 2 Content"); builder.insertCell(); builder.getCellFormat().setWidth(200.0); builder.write("Row 2, Cell 3 Content."); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.CreateFormattedTable.docx");
isAtEndOfParagraph | |
public boolean isAtEndOfParagraph() |
Example:
Shows how to move a DocumentBuilder to different nodes in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start a bookmark and add content to it using a DocumentBuilder builder.startBookmark("MyBookmark"); builder.writeln("Bookmark contents."); builder.endBookmark("MyBookmark"); // The node that the DocumentBuilder is currently at is past the boundaries of the bookmark Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild()); // If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this builder.moveToBookmark("MyBookmark"); // Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild()); // We can move the builder to an individual node, // which in this case will be the first node of the first paragraph, like this builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0)); Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType()); Assert.assertTrue(builder.isAtStartOfParagraph()); // A shorter way of moving the very start/end of a document is with these methods builder.moveToDocumentEnd(); Assert.assertTrue(builder.isAtEndOfParagraph()); builder.moveToDocumentStart(); Assert.assertTrue(builder.isAtStartOfParagraph());
isAtStartOfParagraph | |
public boolean isAtStartOfParagraph() |
Example:
Shows how to move a DocumentBuilder to different nodes in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start a bookmark and add content to it using a DocumentBuilder builder.startBookmark("MyBookmark"); builder.writeln("Bookmark contents."); builder.endBookmark("MyBookmark"); // The node that the DocumentBuilder is currently at is past the boundaries of the bookmark Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild()); // If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this builder.moveToBookmark("MyBookmark"); // Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild()); // We can move the builder to an individual node, // which in this case will be the first node of the first paragraph, like this builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0)); Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType()); Assert.assertTrue(builder.isAtStartOfParagraph()); // A shorter way of moving the very start/end of a document is with these methods builder.moveToDocumentEnd(); Assert.assertTrue(builder.isAtEndOfParagraph()); builder.moveToDocumentStart(); Assert.assertTrue(builder.isAtStartOfParagraph());
getItalic/setItalic | |
public boolean getItalic() / public void setItalic(boolean value) |
Example:
Shows how to fill MERGEFIELDs with data with a DocumentBuilder and without a mail merge.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert some MERGEFIELDS, which accept data from columns of the same name in a data source during a mail merge builder.insertField(" MERGEFIELD Chairman "); builder.insertField(" MERGEFIELD ChiefFinancialOfficer "); builder.insertField(" MERGEFIELD ChiefTechnologyOfficer "); // They can also be filled in manually like this builder.moveToMergeField("Chairman"); builder.setBold(true); builder.writeln("John Doe"); builder.moveToMergeField("ChiefFinancialOfficer"); builder.setItalic(true); builder.writeln("Jane Doe"); builder.moveToMergeField("ChiefTechnologyOfficer"); builder.setItalic(true); builder.writeln("John Bloggs"); doc.save(getArtifactsDir() + "DocumentBuilder.FillMergeFields.docx");
getListFormat | |
public ListFormat getListFormat() |
Example:
Shows how to apply default bulleted or numbered list formatting to paragraphs when using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.writeln("Aspose.Words allows:"); builder.writeln(); // Start a numbered list with default formatting builder.getListFormat().applyNumberDefault(); builder.writeln("Opening documents from different formats:"); Assert.assertEquals(0, builder.getListFormat().getListLevelNumber()); // Go to second list level, add more text builder.getListFormat().listIndent(); Assert.assertEquals(1, builder.getListFormat().getListLevelNumber()); builder.writeln("DOC"); builder.writeln("PDF"); builder.writeln("HTML"); // Outdent to the first list level builder.getListFormat().listOutdent(); Assert.assertEquals(0, builder.getListFormat().getListLevelNumber()); builder.writeln("Processing documents"); builder.writeln("Saving documents in different formats:"); // Indent the list level again builder.getListFormat().listIndent(); builder.writeln("DOC"); builder.writeln("PDF"); builder.writeln("HTML"); builder.writeln("MHTML"); builder.writeln("Plain text"); // Outdent the list level again builder.getListFormat().listOutdent(); builder.writeln("Doing many other things!"); // End the numbered list builder.getListFormat().removeNumbers(); builder.writeln(); builder.writeln("Aspose.Words main advantages are:"); builder.writeln(); // Start a bulleted list with default formatting builder.getListFormat().applyBulletDefault(); builder.writeln("Great performance"); builder.writeln("High reliability"); builder.writeln("Quality code and working"); builder.writeln("Wide variety of features"); builder.writeln("Easy to understand API"); // End the bulleted list builder.getListFormat().removeNumbers(); doc.save(getArtifactsDir() + "Lists.ApplyDefaultBulletsAndNumbers.docx");
getPageSetup | |
public PageSetup getPageSetup() |
Example:
Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Modify the first section in the document builder.getPageSetup().setOrientation(Orientation.LANDSCAPE); builder.getPageSetup().setVerticalAlignment(PageVerticalAlignment.CENTER); builder.writeln("Section 1, landscape oriented and text vertically centered."); // Start a new section and reset its formatting to defaults builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE); builder.getPageSetup().clearFormatting(); builder.writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment."); doc.save(getArtifactsDir() + "PageSetup.ClearFormatting.docx");
getParagraphFormat | |
public ParagraphFormat getParagraphFormat() |
Example:
Shows how to create a formatted table using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Make the header row builder.insertCell(); // Set the left indent for the table. Table wide formatting must be applied after // at least one row is present in the table table.setLeftIndent(20.0); // Set height and define the height rule for the header row builder.getRowFormat().setHeight(40.0); builder.getRowFormat().setHeightRule(HeightRule.AT_LEAST); // Some special features for the header row builder.getCellFormat().getShading().setBackgroundPatternColor(new Color(198, 217, 241)); builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getFont().setSize(16); builder.getFont().setName("Arial"); builder.getFont().setBold(true); builder.getCellFormat().setWidth(100.0); builder.write("Header Row,\n Cell 1"); // We don't need to specify the width of this cell because it's inherited from the previous cell builder.insertCell(); builder.write("Header Row,\n Cell 2"); builder.insertCell(); builder.getCellFormat().setWidth(200.0); builder.write("Header Row,\n Cell 3"); builder.endRow(); // Set features for the other rows and cells builder.getCellFormat().getShading().setBackgroundPatternColor(Color.WHITE); builder.getCellFormat().setWidth(100.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); // Reset height and define a different height rule for table body builder.getRowFormat().setHeight(30.0); builder.getRowFormat().setHeightRule(HeightRule.AUTO); builder.insertCell(); // Reset font formatting builder.getFont().setSize(12); builder.getFont().setBold(false); // Build the other cells builder.write("Row 1, Cell 1 Content"); builder.insertCell(); builder.write("Row 1, Cell 2 Content"); builder.insertCell(); builder.getCellFormat().setWidth(200.0); builder.write("Row 1, Cell 3 Content"); builder.endRow(); builder.insertCell(); builder.getCellFormat().setWidth(100.0); builder.write("Row 2, Cell 1 Content"); builder.insertCell(); builder.write("Row 2, Cell 2 Content"); builder.insertCell(); builder.getCellFormat().setWidth(200.0); builder.write("Row 2, Cell 3 Content."); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.CreateFormattedTable.docx");
getRowFormat | |
public RowFormat getRowFormat() |
Example:
Shows how to create a table that contains a single cell and apply row formatting.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); builder.insertCell(); // Set the row formatting RowFormat rowFormat = builder.getRowFormat(); rowFormat.setHeight(100.0); rowFormat.setHeightRule(HeightRule.EXACTLY); // These formatting properties are set on the table and are applied to all rows in the table table.setLeftPadding(30.0); table.setRightPadding(30.0); table.setTopPadding(30.0); table.setBottomPadding(30.0); builder.writeln("Contents of formatted row."); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.DocumentBuilderSetRowFormatting.docx");
Example:
Shows how to build a formatted table that contains 2 rows and 2 columns.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Insert a cell builder.insertCell(); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.write("This is row 1 cell 1"); // Use fixed column widths table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); // 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.0); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("This is row 2 cell 1"); // Insert a cell builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("This is row 2 cell 2"); builder.endRow(); builder.endTable();
Example:
Shows how to build a nice bordered table.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start building a table builder.startTable(); // Set the appropriate paragraph, cell, and row formatting. The formatting properties are preserved // until they are explicitly modified so there's no need to set them for each row or cell builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getCellFormat().clearFormatting(); builder.getCellFormat().setWidth(150.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN); builder.getCellFormat().setWrapText(false); builder.getCellFormat().setFitText(true); builder.getRowFormat().clearFormatting(); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getRowFormat().setHeight(50.0); builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D); builder.getRowFormat().getBorders().setColor(Color.ORANGE); builder.insertCell(); builder.write("Row 1, Col 1"); builder.insertCell(); builder.write("Row 1, Col 2"); builder.endRow(); // Remove the shading (clear background) builder.getCellFormat().getShading().clearFormatting(); builder.insertCell(); builder.write("Row 2, Col 1"); builder.insertCell(); builder.write("Row 2, Col 2"); builder.endRow(); builder.insertCell(); // Make the row height bigger so that a vertically oriented text could fit into cells builder.getRowFormat().setHeight(150.0); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("Row 3, Col 1"); builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("Row 3, Col 2"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertTable.docx");
getUnderline/setUnderline | |
public int getUnderline() / public void setUnderline(int value) |
Example:
Shows how to set and edit a document builder's underline.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Set a new style for our underline builder.setUnderline(Underline.DASH); // Same object as DocumentBuilder.Font.Underline Assert.assertEquals(builder.getFont().getUnderline(), builder.getUnderline()); Assert.assertEquals(builder.getFont().getUnderline(), Underline.DASH); // These properties will be applied to the underline as well builder.getFont().setColor(Color.BLUE); builder.getFont().setSize(32.0); builder.writeln("Underlined text."); doc.save(getArtifactsDir() + "DocumentBuilder.InsertUnderline.docx");
Method Detail |
---|
deleteRow | |
public Row deleteRow(int tableIndex, int rowIndex) |
If the cursor is inside the row that is being deleted, the cursor is moved out to the next row or to the next paragraph after the table.
If you delete a row from a table that contains only one row, the whole table is deleted.
For the index parameters, when index is greater than or equal to 0, it specifies an index from the beginning with 0 being the first element. When index is less than 0, it specified an index from the end with -1 being the last element.
tableIndex
- The index of the table.rowIndex
- The index of the row in the table.Example:
Shows how to delete a row from a table.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table with 2 rows Table table = builder.startTable(); builder.insertCell(); builder.write("Cell 1"); builder.insertCell(); builder.write("Cell 2"); builder.endRow(); builder.insertCell(); builder.write("Cell 3"); builder.insertCell(); builder.write("Cell 4"); builder.endTable(); Assert.assertEquals(2, table.getRows().getCount()); // Delete the first row of the first table in the document builder.deleteRow(0, 0); Assert.assertEquals(1, table.getRows().getCount());
endBookmark | |
public BookmarkEnd endBookmark(java.lang.String bookmarkName) |
Bookmarks in a document can overlap and span any range. To create a valid bookmark you need to
call both
Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.
bookmarkName
- Name of the bookmark.Example:
Shows how to insert a hyperlink referencing a local bookmark.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.startBookmark("Bookmark1"); builder.write("Bookmarked text."); builder.endBookmark("Bookmark1"); builder.writeln("Some other text"); // Specify font formatting for the hyperlink builder.getFont().setColor(Color.BLUE); builder.getFont().setUnderline(Underline.SINGLE); // Insert hyperlink // Switch \o is used to provide hyperlink tip text builder.insertHyperlink("Hyperlink Text", "Bookmark1\" \\o \"Hyperlink Tip", true); // Clear hyperlink formatting builder.getFont().clearFormatting(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertHyperlinkToLocalBookmark.docx");
Example:
Shows how to add some text into the document and encloses the text in a bookmark using DocumentBuilder.DocumentBuilder builder = new DocumentBuilder(); builder.startBookmark("MyBookmark"); builder.writeln("Text inside a bookmark."); builder.endBookmark("MyBookmark");
endEditableRange | |
public EditableRangeEnd endEditableRange() |
Editable range in a document can overlap and span any range. To create a valid editable range you need to
call both
Badly formed editable range will be ignored when the document is saved.
Example:
Shows how to start and end an editable range.public void createEditableRanges() throws Exception { Document doc = new Document(getMyDir() + "Document.docx"); DocumentBuilder builder = new DocumentBuilder(doc); // Start an editable range EditableRangeStart edRange1Start = builder.startEditableRange(); // An EditableRange object is created for the EditableRangeStart that we just made EditableRange editableRange1 = edRange1Start.getEditableRange(); // Put something inside the editable range builder.writeln("Paragraph inside first editable range"); // An editable range is well-formed if it has a start and an end // Multiple editable ranges can be nested and overlapping EditableRangeEnd edRange1End = builder.endEditableRange(); // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with EditableRangeStart edRange2Start = builder.startEditableRange(); builder.writeln("Paragraph inside second editable range"); EditableRange editableRange2 = edRange2Start.getEditableRange(); EditableRangeEnd edRange2End = builder.endEditableRange(edRange2Start); // Editable range starts and ends have their own respective node types Assert.assertEquals(edRange1Start.getNodeType(), NodeType.EDITABLE_RANGE_START); Assert.assertEquals(edRange1End.getNodeType(), NodeType.EDITABLE_RANGE_END); // Editable range IDs are unique and set automatically Assert.assertEquals(editableRange1.getId(), 0); Assert.assertEquals(editableRange2.getId(), 1); // Editable range starts and ends always belong to a range Assert.assertEquals(editableRange1.getEditableRangeStart(), edRange1Start); Assert.assertEquals(editableRange1.getEditableRangeEnd(), edRange1End); // They also inherit the ID of the entire editable range that they belong to Assert.assertEquals(editableRange1.getId(), edRange1Start.getId()); Assert.assertEquals(editableRange1.getId(), edRange1End.getId()); Assert.assertEquals(editableRange2.getId(), edRange2Start.getEditableRange().getId()); Assert.assertEquals(editableRange2.getId(), edRange2End.getEditableRangeStart().getEditableRange().getId()); // If the editable range was found in a document, it will probably have something in the single user property // But if we make one programmatically, the property is empty by default Assert.assertEquals(editableRange1.getSingleUser(), ""); // We have to set it ourselves if we want the ranges to belong to somebody editableRange1.setSingleUser("john.doe@myoffice.com"); editableRange2.setSingleUser("jane.doe@myoffice.com"); // Initialize a custom visitor for editable ranges that will print their contents EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter(); // Both the start and end of an editable range can accept visitors, but not the editable range itself edRange1Start.accept(editableRangeReader); edRange2End.accept(editableRangeReader); // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor editableRangeReader.reset(); doc.accept(editableRangeReader); System.out.println(editableRangeReader.toText()); } /// <summary> /// Visitor implementation that prints attributes and contents of ranges. /// </summary> public static class EditableRangeInfoPrinter extends DocumentVisitor { public EditableRangeInfoPrinter() { mBuilder = new StringBuilder(); } public String toText() { return mBuilder.toString(); } public void reset() { mBuilder = new StringBuilder(); mInsideEditableRange = false; } /// <summary> /// Called when an EditableRangeStart node is encountered in the document. /// </summary> public int visitEditableRangeStart(final EditableRangeStart editableRangeStart) { mBuilder.append(" -- Editable range found! -- " + "\r\n"); mBuilder.append("\tID: " + editableRangeStart.getId() + "\r\n"); mBuilder.append("\tUser: " + editableRangeStart.getEditableRange().getSingleUser() + "\r\n"); mBuilder.append("\tContents: " + "\r\n"); mInsideEditableRange = true; // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } /// <summary> /// Called when an EditableRangeEnd node is encountered in the document. /// </summary> public int visitEditableRangeEnd(final EditableRangeEnd editableRangeEnd) { mBuilder.append(" -- End of editable range -- " + "\r\n"); mInsideEditableRange = false; // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded. /// </summary> public int visitRun(final Run run) { if (mInsideEditableRange) { mBuilder.append("\t\"" + run.getText() + "\"" + "\r\n"); } // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } private boolean mInsideEditableRange; private StringBuilder mBuilder; }
endEditableRange | |
public EditableRangeEnd endEditableRange(EditableRangeStart start) |
Use this overload during creating nested editable ranges.
Editable range in a document can overlap and span any range. To create a valid editable range you need to
call both
Badly formed editable range will be ignored when the document is saved.
start
- This editable range start.Example:
Shows how to start and end an editable range.public void createEditableRanges() throws Exception { Document doc = new Document(getMyDir() + "Document.docx"); DocumentBuilder builder = new DocumentBuilder(doc); // Start an editable range EditableRangeStart edRange1Start = builder.startEditableRange(); // An EditableRange object is created for the EditableRangeStart that we just made EditableRange editableRange1 = edRange1Start.getEditableRange(); // Put something inside the editable range builder.writeln("Paragraph inside first editable range"); // An editable range is well-formed if it has a start and an end // Multiple editable ranges can be nested and overlapping EditableRangeEnd edRange1End = builder.endEditableRange(); // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with EditableRangeStart edRange2Start = builder.startEditableRange(); builder.writeln("Paragraph inside second editable range"); EditableRange editableRange2 = edRange2Start.getEditableRange(); EditableRangeEnd edRange2End = builder.endEditableRange(edRange2Start); // Editable range starts and ends have their own respective node types Assert.assertEquals(edRange1Start.getNodeType(), NodeType.EDITABLE_RANGE_START); Assert.assertEquals(edRange1End.getNodeType(), NodeType.EDITABLE_RANGE_END); // Editable range IDs are unique and set automatically Assert.assertEquals(editableRange1.getId(), 0); Assert.assertEquals(editableRange2.getId(), 1); // Editable range starts and ends always belong to a range Assert.assertEquals(editableRange1.getEditableRangeStart(), edRange1Start); Assert.assertEquals(editableRange1.getEditableRangeEnd(), edRange1End); // They also inherit the ID of the entire editable range that they belong to Assert.assertEquals(editableRange1.getId(), edRange1Start.getId()); Assert.assertEquals(editableRange1.getId(), edRange1End.getId()); Assert.assertEquals(editableRange2.getId(), edRange2Start.getEditableRange().getId()); Assert.assertEquals(editableRange2.getId(), edRange2End.getEditableRangeStart().getEditableRange().getId()); // If the editable range was found in a document, it will probably have something in the single user property // But if we make one programmatically, the property is empty by default Assert.assertEquals(editableRange1.getSingleUser(), ""); // We have to set it ourselves if we want the ranges to belong to somebody editableRange1.setSingleUser("john.doe@myoffice.com"); editableRange2.setSingleUser("jane.doe@myoffice.com"); // Initialize a custom visitor for editable ranges that will print their contents EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter(); // Both the start and end of an editable range can accept visitors, but not the editable range itself edRange1Start.accept(editableRangeReader); edRange2End.accept(editableRangeReader); // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor editableRangeReader.reset(); doc.accept(editableRangeReader); System.out.println(editableRangeReader.toText()); } /// <summary> /// Visitor implementation that prints attributes and contents of ranges. /// </summary> public static class EditableRangeInfoPrinter extends DocumentVisitor { public EditableRangeInfoPrinter() { mBuilder = new StringBuilder(); } public String toText() { return mBuilder.toString(); } public void reset() { mBuilder = new StringBuilder(); mInsideEditableRange = false; } /// <summary> /// Called when an EditableRangeStart node is encountered in the document. /// </summary> public int visitEditableRangeStart(final EditableRangeStart editableRangeStart) { mBuilder.append(" -- Editable range found! -- " + "\r\n"); mBuilder.append("\tID: " + editableRangeStart.getId() + "\r\n"); mBuilder.append("\tUser: " + editableRangeStart.getEditableRange().getSingleUser() + "\r\n"); mBuilder.append("\tContents: " + "\r\n"); mInsideEditableRange = true; // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } /// <summary> /// Called when an EditableRangeEnd node is encountered in the document. /// </summary> public int visitEditableRangeEnd(final EditableRangeEnd editableRangeEnd) { mBuilder.append(" -- End of editable range -- " + "\r\n"); mInsideEditableRange = false; // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded. /// </summary> public int visitRun(final Run run) { if (mInsideEditableRange) { mBuilder.append("\t\"" + run.getText() + "\"" + "\r\n"); } // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } private boolean mInsideEditableRange; private StringBuilder mBuilder; }
endRow | |
public Row endRow() |
Call EndRow to end a table row. If you call
Use the
Example:
Shows how to build a nice bordered table.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start building a table builder.startTable(); // Set the appropriate paragraph, cell, and row formatting. The formatting properties are preserved // until they are explicitly modified so there's no need to set them for each row or cell builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getCellFormat().clearFormatting(); builder.getCellFormat().setWidth(150.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN); builder.getCellFormat().setWrapText(false); builder.getCellFormat().setFitText(true); builder.getRowFormat().clearFormatting(); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getRowFormat().setHeight(50.0); builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D); builder.getRowFormat().getBorders().setColor(Color.ORANGE); builder.insertCell(); builder.write("Row 1, Col 1"); builder.insertCell(); builder.write("Row 1, Col 2"); builder.endRow(); // Remove the shading (clear background) builder.getCellFormat().getShading().clearFormatting(); builder.insertCell(); builder.write("Row 2, Col 1"); builder.insertCell(); builder.write("Row 2, Col 2"); builder.endRow(); builder.insertCell(); // Make the row height bigger so that a vertically oriented text could fit into cells builder.getRowFormat().setHeight(150.0); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("Row 3, Col 1"); builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("Row 3, Col 2"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertTable.docx");
Example:
Shows how to build a formatted table that contains 2 rows and 2 columns.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Insert a cell builder.insertCell(); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.write("This is row 1 cell 1"); // Use fixed column widths table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); // 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.0); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("This is row 2 cell 1"); // Insert a cell builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("This is row 2 cell 2"); builder.endRow(); builder.endTable();
Example:
Creates a table with two columns with cells merged vertically in the first column.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertCell(); builder.getCellFormat().setVerticalMerge(CellMerge.FIRST); builder.write("Text in merged cells."); builder.insertCell(); builder.getCellFormat().setVerticalMerge(CellMerge.NONE); builder.write("Text in one cell"); builder.endRow(); builder.insertCell(); // This cell is vertically merged to the cell above and should be empty. builder.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS); builder.insertCell(); builder.getCellFormat().setVerticalMerge(CellMerge.NONE); builder.write("Text in another cell"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "CellFormat.VerticalMerge.docx");
endTable | |
public Table endTable() |
This method should be called only once after
Example:
Shows how to build a nice bordered table.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start building a table builder.startTable(); // Set the appropriate paragraph, cell, and row formatting. The formatting properties are preserved // until they are explicitly modified so there's no need to set them for each row or cell builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getCellFormat().clearFormatting(); builder.getCellFormat().setWidth(150.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN); builder.getCellFormat().setWrapText(false); builder.getCellFormat().setFitText(true); builder.getRowFormat().clearFormatting(); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getRowFormat().setHeight(50.0); builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D); builder.getRowFormat().getBorders().setColor(Color.ORANGE); builder.insertCell(); builder.write("Row 1, Col 1"); builder.insertCell(); builder.write("Row 1, Col 2"); builder.endRow(); // Remove the shading (clear background) builder.getCellFormat().getShading().clearFormatting(); builder.insertCell(); builder.write("Row 2, Col 1"); builder.insertCell(); builder.write("Row 2, Col 2"); builder.endRow(); builder.insertCell(); // Make the row height bigger so that a vertically oriented text could fit into cells builder.getRowFormat().setHeight(150.0); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("Row 3, Col 1"); builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("Row 3, Col 2"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertTable.docx");
Example:
Shows how to build a formatted table that contains 2 rows and 2 columns.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Insert a cell builder.insertCell(); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.write("This is row 1 cell 1"); // Use fixed column widths table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); // 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.0); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("This is row 2 cell 1"); // Insert a cell builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("This is row 2 cell 2"); builder.endRow(); builder.endTable();
Example:
Shows how to create a table that contains a single formatted cell.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.startTable(); builder.insertCell(); // Set the cell formatting CellFormat cellFormat = builder.getCellFormat(); cellFormat.setWidth(250.0); cellFormat.setLeftPadding(30.0); cellFormat.setRightPadding(30.0); cellFormat.setTopPadding(30.0); cellFormat.setBottomPadding(30.0); builder.write("Formatted cell"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.DocumentBuilderSetCellFormatting.docx");
insertBreak | |
public void insertBreak(int breakType) |
breakType
- A Example:
Shows how to insert a Table of contents (TOC) into a document using heading styles as entries.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table of contents at the beginning of the document, // and set it to pick up paragraphs with headings of levels 1 to 3 and entries to act like hyperlinks builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u"); // Start the actual document content on the second page builder.insertBreak(BreakType.PAGE_BREAK); // Build a document with complex structure by applying different heading styles thus creating TOC entries // The heading levels we use below will affect the list levels in which these items will appear in the TOC, // and only levels 1-3 will be picked up by our TOC due to its settings 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"); // Call the method below to update the TOC and save doc.updateFields(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertToc.docx");
Example:
Shows how to create headers and footers in a document using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Specify that we want headers and footers different for first, even and odd pages builder.getPageSetup().setDifferentFirstPageHeaderFooter(true); builder.getPageSetup().setOddAndEvenPagesHeaderFooter(true); // Create the headers builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST); builder.write("Header for the first page"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_EVEN); builder.write("Header for even pages"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); builder.write("Header for all other pages"); // Create three pages in the document builder.moveToSection(0); builder.writeln("Page1"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page2"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page3"); doc.save(getArtifactsDir() + "DocumentBuilder.HeadersAndFooters.docx");
Example:
Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Modify the first section in the document builder.getPageSetup().setOrientation(Orientation.LANDSCAPE); builder.getPageSetup().setVerticalAlignment(PageVerticalAlignment.CENTER); builder.writeln("Section 1, landscape oriented and text vertically centered."); // Start a new section and reset its formatting to defaults builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE); builder.getPageSetup().clearFormatting(); builder.writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment."); doc.save(getArtifactsDir() + "PageSetup.ClearFormatting.docx");
insertCell | |
public Cell insertCell() |
To start a table, just call InsertCell. After this, any content you add using
other methods of the
To start a new cell in the same row, call InsertCell again.
To end a table row call
Use the
Example:
Shows how to build a nice bordered table.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start building a table builder.startTable(); // Set the appropriate paragraph, cell, and row formatting. The formatting properties are preserved // until they are explicitly modified so there's no need to set them for each row or cell builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getCellFormat().clearFormatting(); builder.getCellFormat().setWidth(150.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN); builder.getCellFormat().setWrapText(false); builder.getCellFormat().setFitText(true); builder.getRowFormat().clearFormatting(); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getRowFormat().setHeight(50.0); builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D); builder.getRowFormat().getBorders().setColor(Color.ORANGE); builder.insertCell(); builder.write("Row 1, Col 1"); builder.insertCell(); builder.write("Row 1, Col 2"); builder.endRow(); // Remove the shading (clear background) builder.getCellFormat().getShading().clearFormatting(); builder.insertCell(); builder.write("Row 2, Col 1"); builder.insertCell(); builder.write("Row 2, Col 2"); builder.endRow(); builder.insertCell(); // Make the row height bigger so that a vertically oriented text could fit into cells builder.getRowFormat().setHeight(150.0); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("Row 3, Col 1"); builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("Row 3, Col 2"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertTable.docx");
Example:
Shows how to create a simple table using DocumentBuilder with default formatting.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // We call this method to start building the table builder.startTable(); builder.insertCell(); builder.write("Row 1, Cell 1 Content."); // Build the second cell builder.insertCell(); builder.write("Row 1, Cell 2 Content."); // Call the following method to end the row and start a new row builder.endRow(); // Build the first cell of the second row builder.insertCell(); builder.write("Row 2, Cell 1 Content."); // Build the second cell. builder.insertCell(); builder.write("Row 2, Cell 2 Content."); builder.endRow(); // Signal that we have finished building the table builder.endTable(); // Save the document to disk doc.save(getArtifactsDir() + "DocumentBuilder.CreateSimpleTable.docx");
insertChart | |
public Shape insertChart(int chartType, double width, double height) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
chartType
- A width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.Example:
Shows how to insert a chart into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertChart(ChartType.PIE, ConvertUtil.pixelToPoint(300.0), ConvertUtil.pixelToPoint(300.0)); doc.save(getArtifactsDir() + "DocumentBuilder.InsertedChartDouble.docx");
insertChart | |
public Shape insertChart(int chartType, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
chartType
- A horzPos
- A left
- Distance in points from the origin to the left side of the image.vertPos
- A top
- Distance in points from the origin to the top side of the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.wrapType
- A Example:
Shows how to insert a chart into a document and specify position and size.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertChart(ChartType.PIE, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilder.InsertedChartRelativePosition.docx");
insertCheckBox | |
public FormField insertCheckBox(java.lang.String name, boolean defaultValue, boolean checkedValue, int size) throws java.lang.Exception |
If you specify a name for the form field, then a bookmark is automatically created with the same name.
name
- The name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.defaultValue
- Default value of the checkbox form field.checkedValue
- Current checked status of the checkbox form field.size
- Specifies the size of the checkbox in points. Specify 0 for MS Word
to calculate the size of the checkbox automatically.Example:
Shows how to insert checkboxes to the document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertCheckBox("", false, false, 0); builder.insertCheckBox("CheckBox_Default", true, true, 50); builder.insertCheckBox("CheckBox_OnlyCheckedValue", true, 100);
insertCheckBox | |
public FormField insertCheckBox(java.lang.String name, boolean checkedValue, int size) throws java.lang.Exception |
If you specify a name for the form field, then a bookmark is automatically created with the same name.
name
- The name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.checkedValue
- Checked status of the checkbox form field.size
- Specifies the size of the checkbox in points. Specify 0 for MS Word
to calculate the size of the checkbox automatically.Example:
Shows how to insert checkboxes to the document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertCheckBox("", false, false, 0); builder.insertCheckBox("CheckBox_Default", true, true, 50); builder.insertCheckBox("CheckBox_OnlyCheckedValue", true, 100);
insertComboBox | |
public FormField insertComboBox(java.lang.String name, java.lang.String[] items, int selectedIndex) throws java.lang.Exception |
If you specify a name for the form field, then a bookmark is automatically created with the same name.
name
- The name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.items
- The items of the ComboBox. Maximum is 25 items.selectedIndex
- The index of the selected item in the ComboBox.Example:
Shows how to build a form field.DocumentBuilder builder = new DocumentBuilder(); // Insert a text form field for input a name builder.insertTextInput("", TextFormFieldType.REGULAR, "", "Enter your name here", 30); // Insert two blank lines builder.writeln(""); builder.writeln(""); String[] items = new String[]{"-- Select your favorite footwear --", "Sneakers", "Oxfords", "Flip-flops", "Other", "I prefer to be barefoot"}; // Insert a combo box to select a footwear type builder.insertComboBox("", items, 0); // Insert 2 blank lines builder.writeln(""); builder.writeln(""); builder.getDocument().save(getArtifactsDir() + "DocumentBuilder.CreateForm.docx");
Example:
Shows how to insert a combobox form field into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); String[] items = {"One", "Two", "Three"}; builder.insertComboBox("DropDown", items, 0);
insertDocument | |
public Node insertDocument(Document srcDoc, int importFormatMode) |
srcDoc
- Source document for inserting.importFormatMode
- A Example:
Shows how to insert a document content into another document keep formatting of inserted document.Document doc = new Document(getMyDir() + "Document.docx"); DocumentBuilder builder = new DocumentBuilder(doc); builder.moveToDocumentEnd(); builder.insertBreak(BreakType.PAGE_BREAK); Document docToInsert = new Document(getMyDir() + "Formatted elements.docx"); builder.insertDocument(docToInsert, ImportFormatMode.KEEP_SOURCE_FORMATTING); builder.getDocument().save(getArtifactsDir() + "DocumentBuilder.InsertDocument.docx");
insertDocument | |
public Node insertDocument(Document srcDoc, int importFormatMode, ImportFormatOptions importFormatOptions) |
srcDoc
- Source document for inserting.importFormatMode
- A importFormatOptions
- Allows to specify options that affect formatting of a result document.Example:
Shows how to resolve styles behavior while inserting documents.Document dstDoc = new Document(); DocumentBuilder builder = new DocumentBuilder(dstDoc); Style myStyle = builder.getDocument().getStyles().add(StyleType.PARAGRAPH, "MyStyle"); myStyle.getFont().setSize(14.0); myStyle.getFont().setName("Courier New"); myStyle.getFont().setColor(Color.BLUE); // Append text with custom style builder.getParagraphFormat().setStyleName(myStyle.getName()); builder.writeln("Hello world!"); // Clone the document, and edit the clone's "MyStyle" style so it is a different color than that of the original // If we append this document to the original, the different styles will clash since they are the same name, and we will need to resolve it Document srcDoc = dstDoc.deepClone(); srcDoc.getStyles().get("MyStyle").getFont().setColor(Color.RED); // When SmartStyleBehavior is enabled, // a source style will be expanded into a direct attributes inside a destination document, // if KeepSourceFormatting importing mode is used ImportFormatOptions options = new ImportFormatOptions(); options.setSmartStyleBehavior(true); builder.insertDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING, options); dstDoc.save(getArtifactsDir() + "DocumentBuilder.SmartStyleBehavior.docx");
insertField | |
public Field insertField(int fieldType, boolean updateField) throws java.lang.Exception |
This method inserts a field into a document.
Aspose.Words can update fields of most types, but not all. For more details see the
fieldType
- A updateField
- Specifies whether to update the field immediately.Example:
Shows how to insert a field into a document using FieldType.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert an AUTHOR field using a DocumentBuilder doc.getBuiltInDocumentProperties().setAuthor("John Doe"); builder.write("This document was written by "); builder.insertField(FieldType.FIELD_AUTHOR, true); // Insert a PAGE field using a DocumentBuilder, but do not immediately update it builder.write("\nThis is page "); builder.insertField(FieldType.FIELD_PAGE, false); // Some fields types, such as ones that display document word/page counts may not keep track of their results in real time, // and will only display an accurate result during a field update // We can defer the updating of those fields until right before we need to see an accurate result // This method will manually update all the fields in a document doc.updateFields(); Assert.assertEquals("1", doc.getRange().getFields().get(1).getResult());
insertField | |
public Field insertField(java.lang.String fieldCode) throws java.lang.Exception |
This method inserts a field into a document and updates the field result immediately.
Aspose.Words can update fields of most types, but not all. For more details see the
fieldCode
- The field code to insert (without curly braces).Example:
Shows how to insert a field into a document by FieldCode.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a simple Date field into the document // When we insert a field through the DocumentBuilder class we can get the // special Field object which contains information about the field Field dateField = builder.insertField("DATE \\* MERGEFORMAT"); // Update this particular field in the document so we can get the FieldResult dateField.update(); // Display some information from this field // The field result is where the last evaluated value is stored. This is what is displayed in the document // When field codes are not showing Assert.assertEquals(LocalDate.now().format(DateTimeFormatter.ofPattern("M/d/YYYY")), dateField.getResult()); // Display the field code which defines the behavior of the field. This can been seen in Microsoft Word by pressing ALT+F9 Assert.assertEquals("DATE \\* MERGEFORMAT", dateField.getFieldCode()); // The field type defines what type of field in the Document this is. In this case the type is "FieldDate" Assert.assertEquals(FieldType.FIELD_DATE, dateField.getType()); // Finally let's completely remove the field from the document. This can easily be done by invoking the Remove method on the object dateField.remove();
Example:
Shows how to insert merge fields and move between them.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertField("MERGEFIELD MyMergeField1 \\* MERGEFORMAT"); builder.insertField("MERGEFIELD MyMergeField2 \\* MERGEFORMAT"); // The second merge field starts immediately after the end of the first // We'll move the builder's cursor to the end of the first so we can split them by text builder.moveToMergeField("MyMergeField1", true, false); Assert.assertEquals(doc.getRange().getFields().get(1).getStart(), builder.getCurrentNode()); builder.write(" Text between our two merge fields. "); doc.save(getArtifactsDir() + "DocumentBuilder.MergeFields.docx");
insertField | |
public Field insertField(java.lang.String fieldCode, java.lang.String fieldValue) |
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 like the value that the formula produces. The field code may also contain field switches that are like 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 ( { } ).
To create a field, you need to specify a field type, field code and a "placeholder" field value. If you are not sure about a particular field code syntax, create the field in Microsoft Word first and switch to see its field code.
Aspose.Words can calculate field results for most of the field types, but this method
does not update the field result automatically. Because the field result is not calculated automatically,
you are expected to pass some string value (or even an empty string) that will be inserted into the field result.
This value will remain in the field result as a placeholder until the field is updated.
To update the field result you can call
fieldCode
- The field code to insert (without curly braces).fieldValue
- The field value to insert. Pass null for fields that do not have a value.Example:
Shows how to control page numbering per section.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.writeln("Section 1"); builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE); builder.writeln("Section 2"); // Use document builder to create a header with a page number field for the first section // The page number will look like "Page V" builder.moveToSection(0); builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); builder.write("Page "); builder.insertField("PAGE", ""); // Set first section page numbering PageSetup pageSetup = doc.getSections().get(0).getPageSetup(); pageSetup.setRestartPageNumbering(true); pageSetup.setPageStartingNumber(5); pageSetup.setPageNumberStyle(NumberStyle.UPPERCASE_ROMAN); // Create a header for the section // The page number will look like " - 10 - ". builder.moveToSection(1); builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.write(" - "); builder.insertField("PAGE", ""); builder.write(" - "); // Set second section page numbering pageSetup = doc.getSections().get(1).getPageSetup(); pageSetup.setPageStartingNumber(10); pageSetup.setRestartPageNumbering(true); pageSetup.setPageNumberStyle(NumberStyle.ARABIC); doc.save(getArtifactsDir() + "PageSetup.PageNumbering.docx");
insertFootnote | |
public Footnote insertFootnote(int footnoteType, java.lang.String footnoteText) |
footnoteType
- A footnoteText
- Specifies the text of the footnote.Example:
Shows how to reference text with a footnote and an endnote.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert some text and mark it with a footnote with the IsAuto attribute set to "true" by default, // so the marker seen in the body text will be auto-numbered at "1", and the footnote will appear at the bottom of the page builder.write("This text will be referenced by a footnote."); builder.insertFootnote(FootnoteType.FOOTNOTE, "Footnote comment regarding referenced text."); // Insert more text and mark it with an endnote with a custom reference mark, // which will be used in place of the number "2" and will set "IsAuto" to false builder.write("This text will be referenced by an endnote."); builder.insertFootnote(FootnoteType.ENDNOTE, "Endnote comment regarding referenced text.", "CustomMark"); // Footnotes always appear at the bottom of the page of their referenced text, so this page break will not affect the footnote // On the other hand, endnotes are always at the end of the document, so this page break will push the endnote down to the next page builder.insertBreak(BreakType.PAGE_BREAK); doc.save(getArtifactsDir() + "DocumentBuilder.InsertFootnote.docx");
insertFootnote | |
public Footnote insertFootnote(int footnoteType, java.lang.String footnoteText, java.lang.String referenceMark) |
footnoteType
- A footnoteText
- Specifies the text of the footnote.referenceMark
- Specifies the custom reference mark of the footnote.Example:
Shows how to reference text with a footnote and an endnote.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert some text and mark it with a footnote with the IsAuto attribute set to "true" by default, // so the marker seen in the body text will be auto-numbered at "1", and the footnote will appear at the bottom of the page builder.write("This text will be referenced by a footnote."); builder.insertFootnote(FootnoteType.FOOTNOTE, "Footnote comment regarding referenced text."); // Insert more text and mark it with an endnote with a custom reference mark, // which will be used in place of the number "2" and will set "IsAuto" to false builder.write("This text will be referenced by an endnote."); builder.insertFootnote(FootnoteType.ENDNOTE, "Endnote comment regarding referenced text.", "CustomMark"); // Footnotes always appear at the bottom of the page of their referenced text, so this page break will not affect the footnote // On the other hand, endnotes are always at the end of the document, so this page break will push the endnote down to the next page builder.insertBreak(BreakType.PAGE_BREAK); doc.save(getArtifactsDir() + "DocumentBuilder.InsertFootnote.docx");
insertHorizontalRule | |
public Shape insertHorizontalRule() throws java.lang.Exception |
Example:
Shows how to insert horizontal rule shape in a document and customize the formatting.// Use a document builder to insert a horizontal rule Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Shape shape = builder.insertHorizontalRule(); HorizontalRuleFormat horizontalRuleFormat = shape.getHorizontalRuleFormat(); horizontalRuleFormat.setAlignment(HorizontalRuleAlignment.CENTER); horizontalRuleFormat.setWidthPercent(70.0); horizontalRuleFormat.setHeight(3.0); horizontalRuleFormat.setColor(Color.BLUE); horizontalRuleFormat.setNoShade(true); Assert.assertTrue(shape.isHorizontalRule()); Assert.assertTrue(shape.getHorizontalRuleFormat().getNoShade());
insertHtml | |
public void insertHtml(java.lang.String html) throws java.lang.Exception |
You can use InsertHtml to insert an HTML fragment or whole HTML document.
html
- An HTML string to insert into the document.Example:
Shows how to mail merge HTML data into a document.public void insertHtml() throws Exception { Document doc = new Document(getMyDir() + "Field sample - MERGEFIELD.docx"); // Add a handler for the MergeField event doc.getMailMerge().setFieldMergingCallback(new HandleMergeFieldInsertHtml()); final String htmlText = "<html>\r\n<h1>Hello world!</h1>\r\n</html>"; // Execute mail merge doc.getMailMerge().execute(new String[]{"htmlField1"}, new String[]{htmlText}); // Save resulting document with a new name doc.save(getArtifactsDir() + "MailMergeEvent.InsertHtml.docx"); } private class HandleMergeFieldInsertHtml implements IFieldMergingCallback { /** * This is called when merge field is actually merged with data in the document. */ public void fieldMerging(final FieldMergingArgs args) throws Exception { // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html' if (args.getDocumentFieldName().startsWith("html") && args.getField().getFieldCode().contains("\\b")) { FieldMergeField field = args.getField(); // Insert the text for this merge field as HTML data, using DocumentBuilder DocumentBuilder builder = new DocumentBuilder(args.getDocument()); builder.moveToMergeField(args.getDocumentFieldName()); builder.write(field.getTextBefore()); builder.insertHtml((String) args.getFieldValue()); // The HTML text itself should not be inserted // We have already inserted it as an HTML args.setText(""); } } public void /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) { // Do nothing } }
Example:
Shows how to insert Html content into a document using a builder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); final String HTML = "<P align='right'>Paragraph right</P>" + "<b>Implicit paragraph left</b>" + "<div align='center'>Div center</div>" + "<h1 align='left'>Heading 1 left.</h1>"; builder.insertHtml(HTML); doc.save(getArtifactsDir() + "DocumentBuilder.InsertHtml.docx");
insertHtml | |
public void insertHtml(java.lang.String html, boolean useBuilderFormatting) throws java.lang.Exception |
You can use InsertHtml to insert an HTML fragment or whole HTML document.
When useBuilderFormatting is false
,
When useBuilderFormatting is true
,
formatting of inserted text is based on
html
- An HTML string to insert into the document.useBuilderFormatting
-
A value indicating whether formatting specified in Example:
Shows how to insert Html content into a document using a builder while applying the builder's formatting.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Set the builder's text alignment builder.getParagraphFormat().setAlignment(ParagraphAlignment.DISTRIBUTED); // If we insert text while setting useBuilderFormatting to true, any formatting applied to the builder will be applied to inserted .html content // However, if the html text has formatting coded into it, that formatting takes precedence over the builder's formatting // In this case, elements with "align" attributes do not get affected by the ParagraphAlignment we specified above 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>", true); doc.save(getArtifactsDir() + "DocumentBuilder.InsertHtmlWithFormatting.docx");
insertHyperlink | |
public Field insertHyperlink(java.lang.String displayText, java.lang.String urlOrBookmark, boolean isBookmark) |
Note that you need to specify font formatting for the hyperlink display text explicitly
using the
This methods internally calls
displayText
- Text of the link to be displayed in the document.urlOrBookmark
- Link destination. Can be a url or a name of a bookmark inside the document.
This method always adds apostrophes at the beginning and end of the url.isBookmark
- True if the previous parameter is a name of a bookmark inside the document;
false is the previous parameter is a URL.Example:
Shows how to use temporarily save and restore character formatting when building a document with DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Set up font formatting and write text that goes before the hyperlink builder.getFont().setName("Arial"); builder.getFont().setSize(24.0); builder.getFont().setBold(true); builder.write("To visit Google, hold Ctrl and click "); // Save the font formatting so we use different formatting for hyperlink and restore old formatting later builder.pushFont(); // Set new font formatting for the hyperlink and insert the hyperlink // The "Hyperlink" style is a Microsoft Word built-in style so we don't have to worry to // create it, it will be created automatically if it does not yet exist in the document builder.getFont().setStyleIdentifier(StyleIdentifier.HYPERLINK); builder.insertHyperlink("here", "http://www.google.com", false); // Restore the formatting that was before the hyperlink builder.popFont(); builder.write(". We hope you enjoyed the example."); doc.save(getArtifactsDir() + "DocumentBuilder.PushPopFont.docx");
Example:
Shows how to insert a hyperlink referencing a local bookmark.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.startBookmark("Bookmark1"); builder.write("Bookmarked text."); builder.endBookmark("Bookmark1"); builder.writeln("Some other text"); // Specify font formatting for the hyperlink builder.getFont().setColor(Color.BLUE); builder.getFont().setUnderline(Underline.SINGLE); // Insert hyperlink // Switch \o is used to provide hyperlink tip text builder.insertHyperlink("Hyperlink Text", "Bookmark1\" \\o \"Hyperlink Tip", true); // Clear hyperlink formatting builder.getFont().clearFormatting(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertHyperlinkToLocalBookmark.docx");
Example:
Shows how to insert a hyperlink into a document using DocumentBuilder.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."); // Holding Ctrl and left clicking on the field in Microsoft Word will take you to the link's address in a web browser doc.save(getArtifactsDir() + "DocumentBuilder.InsertHyperlink.docx");
insertImage | |
public Shape insertImage(byte[] imageBytes) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
imageBytes
- The byte array that contains the image.Example:
Shows different solutions of how to import an image into a document from a byte array.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); byte[] imageByteArray = DocumentHelper.getBytesFromStream(new FileInputStream(getImageDir() + "Logo.jpg")); builder.writeln("\nInserted image from byte array: "); builder.insertImage(imageByteArray); builder.writeln("\nInserted image from byte array with a custom size: "); builder.insertImage(imageByteArray, ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); builder.writeln("\nInserted image from byte array using relative positions: "); builder.insertImage(imageByteArray, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromByteArray.docx");
insertImage | |
public Shape insertImage(byte[] imageBytes, double width, double height) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
imageBytes
- The byte array that contains the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.Example:
Shows different solutions of how to import an image into a document from a byte array.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); byte[] imageByteArray = DocumentHelper.getBytesFromStream(new FileInputStream(getImageDir() + "Logo.jpg")); builder.writeln("\nInserted image from byte array: "); builder.insertImage(imageByteArray); builder.writeln("\nInserted image from byte array with a custom size: "); builder.insertImage(imageByteArray, ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); builder.writeln("\nInserted image from byte array using relative positions: "); builder.insertImage(imageByteArray, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromByteArray.docx");
insertImage | |
public Shape insertImage(byte[] imageBytes, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
imageBytes
- The byte array that contains the image.horzPos
- A left
- Distance in points from the origin to the left side of the image.vertPos
- A top
- Distance in points from the origin to the top side of the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.wrapType
- A Example:
Shows different solutions of how to import an image into a document from a byte array.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); byte[] imageByteArray = DocumentHelper.getBytesFromStream(new FileInputStream(getImageDir() + "Logo.jpg")); builder.writeln("\nInserted image from byte array: "); builder.insertImage(imageByteArray); builder.writeln("\nInserted image from byte array with a custom size: "); builder.insertImage(imageByteArray, ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); builder.writeln("\nInserted image from byte array using relative positions: "); builder.insertImage(imageByteArray, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromByteArray.docx");
insertImage | |
public Shape insertImage(java.awt.image.BufferedImage image) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
Aspose.Words will insert the image in the PNG format and with default settings. If you want to insert a BufferedImage in
another format or with other settings, you need to save the image into a byte array and use
image
- The image to insert into the document.Example:
Shows how to a watermark image into a document using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // The best place for the watermark image is in the header or footer so it is shown on every page builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); BufferedImage image = ImageIO.read(new File(getImageDir() + "Transparent background logo.png")); // Insert a floating picture Shape shape = builder.insertImage(image); shape.setWrapType(WrapType.NONE); shape.setBehindText(true); shape.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); shape.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); // Calculate image left and top position so it appears in the center of the page shape.setLeft((builder.getPageSetup().getPageWidth() - shape.getWidth()) / 2.0); shape.setTop((builder.getPageSetup().getPageHeight() - shape.getHeight()) / 2.0); doc.save(getArtifactsDir() + "DocumentBuilder.InsertWatermark.docx");
insertImage | |
public Shape insertImage(java.awt.image.BufferedImage image, double width, double height) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
Aspose.Words will insert the image in the PNG format and with default settings. If you want to insert a BufferedImage in
another format or with other settings, you need to save the image into a byte array and use
image
- The image to insert into the document.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.Example:
Shows different solutions of how to import an image into a document from Image class.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); BufferedImage image = ImageIO.read(new File(getImageDir() + "Logo.jpg")); builder.writeln("\nInserted image from Image class: "); builder.insertImage(image); builder.writeln("\nInserted image from Image class with a custom size: "); builder.insertImage(image, ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); builder.writeln("\nInserted image from Image class using relative positions: "); builder.insertImage(image, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromImageClass.docx");
insertImage | |
public Shape insertImage(java.awt.image.BufferedImage image, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
Aspose.Words will insert the image in the PNG format and with default settings. If you want to insert a BufferedImage in
another format or with other settings, you need to save the image into a byte array and use
image
- The image to insert into the document.horzPos
- A left
- Distance in points from the origin to the left side of the image.vertPos
- A top
- Distance in points from the origin to the top side of the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.wrapType
- A Example:
Shows different solutions of how to import an image into a document from Image class.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); BufferedImage image = ImageIO.read(new File(getImageDir() + "Logo.jpg")); builder.writeln("\nInserted image from Image class: "); builder.insertImage(image); builder.writeln("\nInserted image from Image class with a custom size: "); builder.insertImage(image, ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); builder.writeln("\nInserted image from Image class using relative positions: "); builder.insertImage(image, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromImageClass.docx");
insertImage | |
public Shape insertImage(java.io.InputStream stream) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
stream
- The stream that contains the image.
The stream will be read from the current position, so one should be careful about stream position.Example:
Shows different solutions of how to import an image into a document from a stream.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Create reusable stream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(getImageDir() + "Logo.jpg"), byteArrayOutputStream); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); try { builder.writeln("Inserted image from stream: "); builder.insertImage(byteArrayInputStream); byteArrayInputStream.reset(); builder.writeln("\nInserted image from stream with a custom size: "); builder.insertImage(byteArrayInputStream, ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); byteArrayInputStream.reset(); builder.writeln("\nInserted image from stream using relative positions: "); builder.insertImage(byteArrayInputStream, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); } finally { if (byteArrayInputStream != null && byteArrayOutputStream != null) { byteArrayInputStream.close(); byteArrayOutputStream.close(); } } doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromStream.docx");
Example:
Shows how to insert an image from a stream.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); InputStream stream = new FileInputStream(getImageDir() + "Logo.jpg"); try { builder.write("Image from stream: "); builder.insertImage(stream); } finally { stream.close(); } doc.save(getArtifactsDir() + "Image.CreateFromStream.docx");
insertImage | |
public Shape insertImage(java.io.InputStream stream, double width, double height) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
stream
- The stream that contains the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.Example:
Shows different solutions of how to import an image into a document from a stream.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Create reusable stream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(getImageDir() + "Logo.jpg"), byteArrayOutputStream); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); try { builder.writeln("Inserted image from stream: "); builder.insertImage(byteArrayInputStream); byteArrayInputStream.reset(); builder.writeln("\nInserted image from stream with a custom size: "); builder.insertImage(byteArrayInputStream, ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); byteArrayInputStream.reset(); builder.writeln("\nInserted image from stream using relative positions: "); builder.insertImage(byteArrayInputStream, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); } finally { if (byteArrayInputStream != null && byteArrayOutputStream != null) { byteArrayInputStream.close(); byteArrayOutputStream.close(); } } doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromStream.docx");
insertImage | |
public Shape insertImage(java.io.InputStream stream, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
stream
- The stream that contains the image.horzPos
- A left
- Distance in points from the origin to the left side of the image.vertPos
- A top
- Distance in points from the origin to the top side of the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.wrapType
- A Example:
Shows different solutions of how to import an image into a document from a stream.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Create reusable stream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(getImageDir() + "Logo.jpg"), byteArrayOutputStream); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); try { builder.writeln("Inserted image from stream: "); builder.insertImage(byteArrayInputStream); byteArrayInputStream.reset(); builder.writeln("\nInserted image from stream with a custom size: "); builder.insertImage(byteArrayInputStream, ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); byteArrayInputStream.reset(); builder.writeln("\nInserted image from stream using relative positions: "); builder.insertImage(byteArrayInputStream, RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); } finally { if (byteArrayInputStream != null && byteArrayOutputStream != null) { byteArrayInputStream.close(); byteArrayOutputStream.close(); } } doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromStream.docx");
insertImage | |
public Shape insertImage(java.lang.String fileName) throws java.lang.Exception |
This overload will automatically download the image before inserting into the document if you specify a remote URI.
You can change the image size, location, positioning method and other settings using the
fileName
- The file with the image. Can be any valid local or remote URI.Example:
Shows different solutions of how to import an image into a document from a string.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.writeln("\nInserted image from string: "); builder.insertImage(getImageDir() + "Logo.jpg"); builder.writeln("\nInserted image from string with a custom size: "); builder.insertImage(getImageDir() + "Transparent background logo.png", ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); builder.writeln("\nInserted image from string using relative positions: "); builder.insertImage(getImageDir() + "Windows Metafile.wmf", RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromString.docx");
Example:
Shows how to insert a floating image in the middle of a page.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // By default, the image is inline Shape shape = builder.insertImage(getImageDir() + "Logo.jpg"); // Make the image float, put it behind text and center on the page shape.setWrapType(WrapType.NONE); shape.setBehindText(true); shape.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); shape.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); shape.setHorizontalAlignment(HorizontalAlignment.CENTER); shape.setVerticalAlignment(VerticalAlignment.CENTER); doc.save(getArtifactsDir() + "Image.CreateFloatingPageCenter.docx");
Example:
Shows how to inserts an image from a URL.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.write("Image from local file: "); builder.insertImage(getImageDir() + "Logo.jpg"); builder.writeln(); builder.write("Image from a URL: "); builder.insertImage(getAsposelogoUri().toURL().openStream()); builder.writeln(); doc.save(getArtifactsDir() + "Image.CreateFromUrl.docx");
insertImage | |
public Shape insertImage(java.lang.String fileName, double width, double height) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
fileName
- The file that contains the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.Example:
Shows different solutions of how to import an image into a document from a string.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.writeln("\nInserted image from string: "); builder.insertImage(getImageDir() + "Logo.jpg"); builder.writeln("\nInserted image from string with a custom size: "); builder.insertImage(getImageDir() + "Transparent background logo.png", ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); builder.writeln("\nInserted image from string using relative positions: "); builder.insertImage(getImageDir() + "Windows Metafile.wmf", RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromString.docx");
insertImage | |
public Shape insertImage(java.lang.String fileName, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
fileName
- The file that contains the image.horzPos
- A left
- Distance in points from the origin to the left side of the image.vertPos
- A top
- Distance in points from the origin to the top side of the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.wrapType
- A Example:
Shows different solutions of how to import an image into a document from a string.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.writeln("\nInserted image from string: "); builder.insertImage(getImageDir() + "Logo.jpg"); builder.writeln("\nInserted image from string with a custom size: "); builder.insertImage(getImageDir() + "Transparent background logo.png", ConvertUtil.pixelToPoint(250.0), ConvertUtil.pixelToPoint(144.0)); builder.writeln("\nInserted image from string using relative positions: "); builder.insertImage(getImageDir() + "Windows Metafile.wmf", RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilderImages.InsertImageFromString.docx");
Example:
Shows how to insert a floating image from a file or URL and retain the original image size in the document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Pass a negative value to the width and height values to specify using the size of the source image builder.insertImage(getImageDir() + "Logo.jpg", RelativeHorizontalPosition.MARGIN, 200.0, RelativeVerticalPosition.MARGIN, 100.0, -1, -1, WrapType.SQUARE);
Example:
Shows how to insert a floating image from a file or URL.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertImage(getImageDir() + "Transparent background logo.png", RelativeHorizontalPosition.MARGIN, 100.0, RelativeVerticalPosition.MARGIN, 100.0, 200.0, 100.0, WrapType.SQUARE);
insertNode | |
public void insertNode(Node node) |
Example:
Shows how to insert a linked image into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); String imageFileName = getImageDir() + "Windows MetaFile.wmf"; builder.write("Image linked, not stored in the document: "); Shape shape = new Shape(builder.getDocument(), ShapeType.IMAGE); shape.setWrapType(WrapType.INLINE); shape.getImageData().setSourceFullName(imageFileName); builder.insertNode(shape); builder.writeln(); builder.write("Image linked and stored in the document: "); shape = new Shape(builder.getDocument(), ShapeType.IMAGE); shape.setWrapType(WrapType.INLINE); shape.getImageData().setSourceFullName(imageFileName); shape.getImageData().setImage(imageFileName); builder.insertNode(shape); builder.writeln(); builder.write("Image stored in the document, but not linked: "); shape = new Shape(builder.getDocument(), ShapeType.IMAGE); shape.setWrapType(WrapType.INLINE); shape.getImageData().setImage(imageFileName); builder.insertNode(shape); builder.writeln(); doc.save(getArtifactsDir() + "Image.CreateLinkedImage.docx");
insertOleObject | |
public Shape insertOleObject(java.io.InputStream stream, java.lang.String progId, boolean asIcon, java.awt.image.BufferedImage presentation) throws java.lang.Exception |
stream
- Stream containing application data.progId
- Programmatic Identifier of OLE object.asIcon
- Specifies either Iconic or Normal mode of OLE object being inserted.presentation
- Image presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.Example:
Shows how to use document builder to embed Ole objects in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Let's take a spreadsheet from our system and insert it into the document InputStream spreadsheetStream = new FileInputStream(getMyDir() + "Spreadsheet.xlsx"); // The spreadsheet can be activated by double clicking the panel that you'll see in the document immediately under the text we will add // We did not set the area to double click as an icon nor did we change its appearance so it looks like a simple panel builder.writeln("Spreadsheet Ole object:"); builder.insertOleObject(spreadsheetStream, "OleObject.xlsx", false, null); // A powerpoint presentation is another type of object we can embed in our document // This time we'll also exercise some control over how it looks InputStream powerpointStream = new FileInputStream(getMyDir() + "Presentation.pptx"); byte[] imageBytes = DocumentHelper.getBytesFromStream(getAsposelogoUri().toURL().openStream()); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes)); // If we double click the image, the powerpoint presentation will open builder.insertParagraph(); builder.writeln("Powerpoint Ole object:"); builder.insertOleObject(powerpointStream, "OleObject.pptx", true, image); doc.save(getArtifactsDir() + "DocumentBuilder.InsertOlePowerpoint.docx");
insertOleObject | |
public Shape insertOleObject(java.lang.String fileName, boolean isLinked, boolean asIcon, java.awt.image.BufferedImage presentation) throws java.lang.Exception |
fileName
- Full path to the file.isLinked
- If true then linked OLE object is inserted otherwise embedded OLE object is inserted.asIcon
- Specifies either Iconic or Normal mode of OLE object being inserted.presentation
- Image presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.Example:
Shows how to insert an OLE object into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert ole object BufferedImage representingImage = ImageIO.read(new File(getImageDir() + "Logo.jpg")); builder.insertOleObject(getMyDir() + "Spreadsheet.xlsx", false, false, representingImage); // Insert ole object with ProgId builder.insertOleObject(getMyDir() + "Spreadsheet.xlsx", "Excel.Sheet", false, true, null); // Insert ole object as Icon // There is one limitation for now: the maximum size of the icon must be 32x32 for the correct display builder.insertOleObjectAsIcon(getMyDir() + "Presentation.pptx", false, getImageDir() + "Logo icon.ico", "Caption (can not be null)"); doc.save(getArtifactsDir() + "DocumentBuilder.InsertOleObject.docx");
insertOleObject | |
public Shape insertOleObject(java.lang.String fileName, java.lang.String progId, boolean isLinked, boolean asIcon, java.awt.image.BufferedImage presentation) throws java.lang.Exception |
fileName
- Full path to the file.progId
- ProgId of OLE object.isLinked
- If true then linked OLE object is inserted otherwise embedded OLE object is inserted.asIcon
- Specifies either Iconic or Normal mode of OLE object being inserted.presentation
- Image presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.Example:
Shows how to insert an OLE object into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert ole object BufferedImage representingImage = ImageIO.read(new File(getImageDir() + "Logo.jpg")); builder.insertOleObject(getMyDir() + "Spreadsheet.xlsx", false, false, representingImage); // Insert ole object with ProgId builder.insertOleObject(getMyDir() + "Spreadsheet.xlsx", "Excel.Sheet", false, true, null); // Insert ole object as Icon // There is one limitation for now: the maximum size of the icon must be 32x32 for the correct display builder.insertOleObjectAsIcon(getMyDir() + "Presentation.pptx", false, getImageDir() + "Logo icon.ico", "Caption (can not be null)"); doc.save(getArtifactsDir() + "DocumentBuilder.InsertOleObject.docx");
insertOleObjectAsIcon | |
public Shape insertOleObjectAsIcon(java.lang.String fileName, boolean isLinked, java.lang.String iconFile, java.lang.String iconCaption) throws java.lang.Exception |
fileName
- Full path to the file.isLinked
-
If true then linked OLE object is inserted otherwise embedded OLE object is inserted.
iconFile
-
Full path to the ICO file. If the value is null, Aspose.Words will use a predefined image.
iconCaption
- Icon caption.Example:
Shows how to insert an OLE object into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert ole object BufferedImage representingImage = ImageIO.read(new File(getImageDir() + "Logo.jpg")); builder.insertOleObject(getMyDir() + "Spreadsheet.xlsx", false, false, representingImage); // Insert ole object with ProgId builder.insertOleObject(getMyDir() + "Spreadsheet.xlsx", "Excel.Sheet", false, true, null); // Insert ole object as Icon // There is one limitation for now: the maximum size of the icon must be 32x32 for the correct display builder.insertOleObjectAsIcon(getMyDir() + "Presentation.pptx", false, getImageDir() + "Logo icon.ico", "Caption (can not be null)"); doc.save(getArtifactsDir() + "DocumentBuilder.InsertOleObject.docx");
insertOnlineVideo | |
public Shape insertOnlineVideo(java.lang.String videoUrl, double width, double height) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
Insertion of online video from the following resources is supported:
If your online video is not displaying correctly, use
The code for embedding video can vary between providers, consult your corresponding provider of choice for details.
videoUrl
- The URL to the video.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.Example:
Shows how to insert online video into a document using video urlDocument doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a video from Youtube builder.insertOnlineVideo("https://youtu.be/t_1LYZ102RA", 360.0, 270.0); // Click on the shape in the output document to watch the video from Microsoft Word doc.save(getArtifactsDir() + "DocumentBuilder.InsertVideoWithUrl.docx");
insertOnlineVideo | |
public Shape insertOnlineVideo(java.lang.String videoUrl, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
Insertion of online video from the following resources is supported:
If your online video is not displaying correctly, use
The code for embedding video can vary between providers, consult your corresponding provider of choice for details.
videoUrl
- The URL to the video.horzPos
- A left
- Distance in points from the origin to the left side of the image.vertPos
- A top
- Distance in points from the origin to the top side of the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.wrapType
- A Example:
Shows how to insert online video into a document using html code.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Visible url String vimeoVideoUrl = "https://vimeo.com/52477838"; // Embed Html code String vimeoEmbedCode = "<iframe src=\"https://player.vimeo.com/video/52477838\" width=\"640\" height=\"360\" frameborder=\"0\" title=\"Aspose\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"; // This video will have an automatically generated thumbnail, and we are setting the size according to its 16:9 aspect ratio builder.writeln("Video with an automatically generated thumbnail at the top left corner of the page:"); builder.insertOnlineVideo(vimeoVideoUrl, RelativeHorizontalPosition.LEFT_MARGIN, 0.0, RelativeVerticalPosition.TOP_MARGIN, 0.0, 320.0, 180.0, WrapType.SQUARE); builder.insertBreak(BreakType.PAGE_BREAK); // We can get an image to use as a custom thumbnail byte[] imageBytes = DocumentHelper.getBytesFromStream(getAsposelogoUri().toURL().openStream()); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes)); // This puts the video where we are with our document builder, with a custom thumbnail and size depending on the size of the image builder.writeln("Custom thumbnail at document builder's cursor:"); builder.insertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, image.getWidth(), image.getHeight()); builder.insertBreak(BreakType.PAGE_BREAK); // We can put the video at the bottom right edge of the page too, but we'll have to take the page margins into account double left = builder.getPageSetup().getRightMargin() - image.getWidth(); double top = builder.getPageSetup().getBottomMargin() - image.getHeight(); // Here we use a custom thumbnail and relative positioning to put it and the bottom right of tha page builder.writeln("Bottom right of page with custom thumbnail:"); builder.insertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, RelativeHorizontalPosition.RIGHT_MARGIN, left, RelativeVerticalPosition.BOTTOM_MARGIN, top, image.getWidth(), image.getHeight(), WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilder.InsertOnlineVideo.docx");
insertOnlineVideo | |
public Shape insertOnlineVideo(java.lang.String videoUrl, java.lang.String videoEmbedCode, byte[] thumbnailImageBytes, double width, double height) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
videoUrl
- The URL to the video.videoEmbedCode
- The embed code for the video.thumbnailImageBytes
- The thumbnail image bytes.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.Example:
Shows how to insert online video into a document using html code.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Visible url String vimeoVideoUrl = "https://vimeo.com/52477838"; // Embed Html code String vimeoEmbedCode = "<iframe src=\"https://player.vimeo.com/video/52477838\" width=\"640\" height=\"360\" frameborder=\"0\" title=\"Aspose\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"; // This video will have an automatically generated thumbnail, and we are setting the size according to its 16:9 aspect ratio builder.writeln("Video with an automatically generated thumbnail at the top left corner of the page:"); builder.insertOnlineVideo(vimeoVideoUrl, RelativeHorizontalPosition.LEFT_MARGIN, 0.0, RelativeVerticalPosition.TOP_MARGIN, 0.0, 320.0, 180.0, WrapType.SQUARE); builder.insertBreak(BreakType.PAGE_BREAK); // We can get an image to use as a custom thumbnail byte[] imageBytes = DocumentHelper.getBytesFromStream(getAsposelogoUri().toURL().openStream()); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes)); // This puts the video where we are with our document builder, with a custom thumbnail and size depending on the size of the image builder.writeln("Custom thumbnail at document builder's cursor:"); builder.insertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, image.getWidth(), image.getHeight()); builder.insertBreak(BreakType.PAGE_BREAK); // We can put the video at the bottom right edge of the page too, but we'll have to take the page margins into account double left = builder.getPageSetup().getRightMargin() - image.getWidth(); double top = builder.getPageSetup().getBottomMargin() - image.getHeight(); // Here we use a custom thumbnail and relative positioning to put it and the bottom right of tha page builder.writeln("Bottom right of page with custom thumbnail:"); builder.insertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, RelativeHorizontalPosition.RIGHT_MARGIN, left, RelativeVerticalPosition.BOTTOM_MARGIN, top, image.getWidth(), image.getHeight(), WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilder.InsertOnlineVideo.docx");
insertOnlineVideo | |
public Shape insertOnlineVideo(java.lang.String videoUrl, java.lang.String videoEmbedCode, byte[] thumbnailImageBytes, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
videoUrl
- The URL to the video.videoEmbedCode
- The embed code for the video.thumbnailImageBytes
- The thumbnail image bytes.horzPos
- A left
- Distance in points from the origin to the left side of the image.vertPos
- A top
- Distance in points from the origin to the top side of the image.width
- The width of the image in points. Can be a negative or zero value to request 100% scale.height
- The height of the image in points. Can be a negative or zero value to request 100% scale.wrapType
- A Example:
Shows how to insert online video into a document using html code.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Visible url String vimeoVideoUrl = "https://vimeo.com/52477838"; // Embed Html code String vimeoEmbedCode = "<iframe src=\"https://player.vimeo.com/video/52477838\" width=\"640\" height=\"360\" frameborder=\"0\" title=\"Aspose\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"; // This video will have an automatically generated thumbnail, and we are setting the size according to its 16:9 aspect ratio builder.writeln("Video with an automatically generated thumbnail at the top left corner of the page:"); builder.insertOnlineVideo(vimeoVideoUrl, RelativeHorizontalPosition.LEFT_MARGIN, 0.0, RelativeVerticalPosition.TOP_MARGIN, 0.0, 320.0, 180.0, WrapType.SQUARE); builder.insertBreak(BreakType.PAGE_BREAK); // We can get an image to use as a custom thumbnail byte[] imageBytes = DocumentHelper.getBytesFromStream(getAsposelogoUri().toURL().openStream()); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes)); // This puts the video where we are with our document builder, with a custom thumbnail and size depending on the size of the image builder.writeln("Custom thumbnail at document builder's cursor:"); builder.insertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, image.getWidth(), image.getHeight()); builder.insertBreak(BreakType.PAGE_BREAK); // We can put the video at the bottom right edge of the page too, but we'll have to take the page margins into account double left = builder.getPageSetup().getRightMargin() - image.getWidth(); double top = builder.getPageSetup().getBottomMargin() - image.getHeight(); // Here we use a custom thumbnail and relative positioning to put it and the bottom right of tha page builder.writeln("Bottom right of page with custom thumbnail:"); builder.insertOnlineVideo(vimeoVideoUrl, vimeoEmbedCode, imageBytes, RelativeHorizontalPosition.RIGHT_MARGIN, left, RelativeVerticalPosition.BOTTOM_MARGIN, top, image.getWidth(), image.getHeight(), WrapType.SQUARE); doc.save(getArtifactsDir() + "DocumentBuilder.InsertOnlineVideo.docx");
insertParagraph | |
public Paragraph insertParagraph() |
Current paragraph formatting specified by the
Breaks the current paragraph in two. After inserting the paragraph, the cursor is placed at the beginning of the new paragraph.
insertShape | |
public Shape insertShape(int shapeType, double width, double height) throws java.lang.Exception |
shapeType
- A width
- The width of the shape in points.height
- The height of the shape in points.Example:
Shows how to insert DML shapes into the document using a document builder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // There are two ways of shape insertion // These methods allow inserting DML shape into the document model // Document must be saved in the format, which supports DML shapes, otherwise, such nodes will be converted // to VML shape, while document saving // 1. Free-floating shape insertion Shape freeFloatingShape = builder.insertShape(ShapeType.TEXT_BOX, RelativeHorizontalPosition.PAGE, 100.0, RelativeVerticalPosition.PAGE, 100.0, 50.0, 50.0, WrapType.NONE); freeFloatingShape.setRotation(30.0); // 2. Inline shape insertion Shape inlineShape = builder.insertShape(ShapeType.TEXT_BOX, 50.0, 50.0); inlineShape.setRotation(30.0); // If you need to create "NonPrimitive" shapes, like SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, // TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, DiagonalCornersRounded // please save the document with "Strict" or "Transitional" compliance which allows saving shape as DML OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(SaveFormat.DOCX); saveOptions.setCompliance(OoxmlCompliance.ISO_29500_2008_TRANSITIONAL); doc.save(getArtifactsDir() + "Shape.ShapeInsertion.docx", saveOptions);
insertShape | |
public Shape insertShape(int shapeType, int horzPos, double left, int vertPos, double top, double width, double height, int wrapType) throws java.lang.Exception |
shapeType
- A horzPos
- A left
- Distance in points from the origin to the left side of the shape.vertPos
- A top
- Distance in points from the origin to the top side of the shape.width
- The width of the shape in points.height
- The width of the shape in points.wrapType
- A Example:
Shows how to insert DML shapes into the document using a document builder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // There are two ways of shape insertion // These methods allow inserting DML shape into the document model // Document must be saved in the format, which supports DML shapes, otherwise, such nodes will be converted // to VML shape, while document saving // 1. Free-floating shape insertion Shape freeFloatingShape = builder.insertShape(ShapeType.TEXT_BOX, RelativeHorizontalPosition.PAGE, 100.0, RelativeVerticalPosition.PAGE, 100.0, 50.0, 50.0, WrapType.NONE); freeFloatingShape.setRotation(30.0); // 2. Inline shape insertion Shape inlineShape = builder.insertShape(ShapeType.TEXT_BOX, 50.0, 50.0); inlineShape.setRotation(30.0); // If you need to create "NonPrimitive" shapes, like SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped, // TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, DiagonalCornersRounded // please save the document with "Strict" or "Transitional" compliance which allows saving shape as DML OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(SaveFormat.DOCX); saveOptions.setCompliance(OoxmlCompliance.ISO_29500_2008_TRANSITIONAL); doc.save(getArtifactsDir() + "Shape.ShapeInsertion.docx", saveOptions);
insertSignatureLine | |
public Shape insertSignatureLine(SignatureLineOptions signatureLineOptions) throws java.lang.Exception |
signatureLineOptions
- The object that stores parameters of creating signature line.Example:
Shows how to sign document with personal certificate and specific signature line.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Date currentDate = new Date(); SignatureLineOptions signatureLineOptions = new SignatureLineOptions(); signatureLineOptions.setSigner("vderyushev"); signatureLineOptions.setSignerTitle("QA"); signatureLineOptions.setEmail("vderyushev@aspose.com"); signatureLineOptions.setShowDate(true); signatureLineOptions.setDefaultInstructions(false); signatureLineOptions.setInstructions("You need more info about signature line"); signatureLineOptions.setAllowComments(true); SignatureLine signatureLine = builder.insertSignatureLine(signatureLineOptions).getSignatureLine(); signatureLine.setProviderId(UUID.fromString("CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2")); doc.save(getArtifactsDir() + "DocumentBuilder.SignatureLineProviderId.docx"); SignOptions signOptions = new SignOptions(); signOptions.setSignatureLineId(signatureLine.getId()); signOptions.setProviderId(signatureLine.getProviderId()); signOptions.setComments("Document was signed by vderyushev"); signOptions.setSignTime(currentDate); CertificateHolder certHolder = CertificateHolder.create(getMyDir() + "morzal.pfx", "aw"); DigitalSignatureUtil.sign(getArtifactsDir() + "DocumentBuilder.SignatureLineProviderId.docx", getArtifactsDir() + "DocumentBuilder.SignatureLineProviderId.Signed.docx", certHolder, signOptions);
insertSignatureLine | |
public Shape insertSignatureLine(SignatureLineOptions signatureLineOptions, int horzPos, double left, int vertPos, double top, int wrapType) throws java.lang.Exception |
You can change the image size, location, positioning method and other settings using the
Aspose.Words will insert the image in the PNG format and with default settings. If you want to insert a BufferedImage in
another format or with other settings, you need to save the image into a byte array and use
signatureLineOptions
- The object that stores parameters of creating signature line.horzPos
- A left
- Distance in points from the origin to the left side of the signature line.vertPos
- A top
- Distance in points from the origin to the top side of the signature line.wrapType
- A Example:
Shows how to insert signature line at the specified position.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); SignatureLineOptions options = new SignatureLineOptions(); options.setSigner("John Doe"); options.setSignerTitle("Manager"); options.setEmail("johndoe@aspose.com"); options.setShowDate(true); options.setDefaultInstructions(false); options.setInstructions("You need more info about signature line"); options.setAllowComments(true); builder.insertSignatureLine(options, RelativeHorizontalPosition.RIGHT_MARGIN, 2.0, RelativeVerticalPosition.PAGE, 3.0, WrapType.INLINE);
insertStyleSeparator | |
public void insertStyleSeparator() |
Example:
Shows how to separate styles from two different paragraphs used in one logical printed paragraph.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Append text in the "Heading 1" style builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1); builder.write("This text is in a Heading style. "); // Insert a style separator builder.insertStyleSeparator(); // The style separator appears in the form of a paragraph break that doesn't start a new line // So, while this looks like one continuous paragraph with two styles in the output document, // it is actually two paragraphs with different styles, but no line break between the first and second paragraph Assert.assertEquals(2, doc.getFirstSection().getBody().getParagraphs().getCount()); // Append text with another style Style paraStyle = builder.getDocument().getStyles().add(StyleType.PARAGRAPH, "MyParaStyle"); paraStyle.getFont().setBold(false); paraStyle.getFont().setSize(8.0); paraStyle.getFont().setName("Arial"); // Set the style of the current paragraph to our custom style // This will apply to only the text after the style separator builder.getParagraphFormat().setStyleName(paraStyle.getName()); builder.write("This text is in a custom style. "); doc.save(getArtifactsDir() + "DocumentBuilder.InsertStyleSeparator.docx");
insertTableOfContents | |
public Field insertTableOfContents(java.lang.String switches) |
This method inserts a TOC (table of contents) field into the document at the current position.
A table of contents in a Word document can be built in a number of ways and formatted using a variety of options. The way the table is built and displayed by Microsoft Word is controlled by the field switches.
The easiest way to specify the switches is to insert and configure a table of contents into a Word document using the Insert->Reference->Index and Tables menu, then switch display of field codes on to see the switches. You can press Alt+F9 in Microsoft Word to toggle display of field codes on or off.
For example, after creating a table of contents, the following field is inserted into the document: { TOC \o "1-3" \h \z \u }. You can copy \o "1-3" \h \z \u and use it as the switches parameter.
Note that InsertTableOfContents will only insert a TOC field, but will not actually build the table of contents. The table of contents is built by Microsoft Word when the field is updated.
If you insert a table of contents using this method and then open the file in Microsoft Word, you will not see the table of contents because the TOC field has not yet been updated.
In Microsoft Word, fields are not automatically updated when a document is opened, but you can update fields in a document at any time by pressing F9.
switches
- The TOC field switches.Example:
Shows how to insert a Table of contents (TOC) into a document using heading styles as entries.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table of contents at the beginning of the document, // and set it to pick up paragraphs with headings of levels 1 to 3 and entries to act like hyperlinks builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u"); // Start the actual document content on the second page builder.insertBreak(BreakType.PAGE_BREAK); // Build a document with complex structure by applying different heading styles thus creating TOC entries // The heading levels we use below will affect the list levels in which these items will appear in the TOC, // and only levels 1-3 will be picked up by our TOC due to its settings 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"); // Call the method below to update the TOC and save doc.updateFields(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertToc.docx");
insertTextInput | |
public FormField insertTextInput(java.lang.String name, int type, java.lang.String format, java.lang.String fieldValue, int maxLength) throws java.lang.Exception |
If you specify a name for the form field, then a bookmark is automatically created with the same name.
name
- The name of the form field. Can be an empty string.type
- A format
- Format string used to format the value of the form field.fieldValue
- Text that will be shown in the field.maxLength
- Maximum length the user can enter into the form field. Set to zero for unlimited length.Example:
Shows how to build a form field.DocumentBuilder builder = new DocumentBuilder(); // Insert a text form field for input a name builder.insertTextInput("", TextFormFieldType.REGULAR, "", "Enter your name here", 30); // Insert two blank lines builder.writeln(""); builder.writeln(""); String[] items = new String[]{"-- Select your favorite footwear --", "Sneakers", "Oxfords", "Flip-flops", "Other", "I prefer to be barefoot"}; // Insert a combo box to select a footwear type builder.insertComboBox("", items, 0); // Insert 2 blank lines builder.writeln(""); builder.writeln(""); builder.getDocument().save(getArtifactsDir() + "DocumentBuilder.CreateForm.docx");
Example:
Shows how to insert form fields, set options and gather them back in for use.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a text input field. The unique name of this field is "TextInput1", the other parameters define // what type of FormField it is, the format of the text, the field result and the maximum text length (0 = no limit) builder.insertTextInput("TextInput1", TextFormFieldType.REGULAR, "", "", 0);
Example:
Shows how to insert a text input form field into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", "Hello", 0);
moveTo | |
public void moveTo(Node node) |
When node is an inline-level node, the cursor is moved to this node and further content will be inserted before that node.
When node is a Paragraph, the cursor is moved to the end of the paragraph and further content will be inserted just before the paragraph break.
When node is a block-level node but not a Paragraph, the cursor is moved to the end of the first paragraph into block-level node and further content will be inserted just before the paragraph break.
node
- The node must be a paragraph or a direct child of a paragraph.Example:
Shows how to move a DocumentBuilder to different nodes in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start a bookmark and add content to it using a DocumentBuilder builder.startBookmark("MyBookmark"); builder.writeln("Bookmark contents."); builder.endBookmark("MyBookmark"); // The node that the DocumentBuilder is currently at is past the boundaries of the bookmark Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild()); // If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this builder.moveToBookmark("MyBookmark"); // Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild()); // We can move the builder to an individual node, // which in this case will be the first node of the first paragraph, like this builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0)); Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType()); Assert.assertTrue(builder.isAtStartOfParagraph()); // A shorter way of moving the very start/end of a document is with these methods builder.moveToDocumentEnd(); Assert.assertTrue(builder.isAtEndOfParagraph()); builder.moveToDocumentStart(); Assert.assertTrue(builder.isAtStartOfParagraph());
Example:
Shows how to move a DocumentBuilder's cursor position to a specified node.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Write a paragraph with the DocumentBuilder builder.writeln("Text 1. "); // Move the DocumentBuilder to the first paragraph of the document and add another paragraph builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getRuns().get(0)); builder.writeln("Text 2. "); // Since we moved to a node before the first paragraph before we added a second paragraph, // the second paragraph will appear in front of the first paragraph Assert.assertEquals("Text 2. \rText 1.", doc.getText().trim()); // We can move the DocumentBuilder back to the end of the document like this // and carry on adding text to the end of the document builder.moveTo(doc.getFirstSection().getBody().getLastParagraph()); builder.writeln("Text 3. "); Assert.assertEquals("Text 2. \rText 1. \rText 3.", doc.getText().trim());
moveToBookmark | |
public boolean moveToBookmark(java.lang.String bookmarkName) throws java.lang.Exception |
Moves the cursor to a position just after the start of the bookmark with the specified name.
The comparison is not case-sensitive. If the bookmark was not found, false is returned and the cursor is not moved.
Inserting new text does not replace existing text of the bookmark.
Note that some bookmarks in the document are assigned to form fields. Moving to such a bookmark and inserting text there inserts the text into the form field code. Although this will not invalidate the form field, the inserted text will not be visible because it becomes part of the field code.
bookmarkName
- The name of the bookmark to move the cursor to.Example:
Shows how to move a DocumentBuilder to different nodes in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start a bookmark and add content to it using a DocumentBuilder builder.startBookmark("MyBookmark"); builder.writeln("Bookmark contents."); builder.endBookmark("MyBookmark"); // The node that the DocumentBuilder is currently at is past the boundaries of the bookmark Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild()); // If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this builder.moveToBookmark("MyBookmark"); // Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild()); // We can move the builder to an individual node, // which in this case will be the first node of the first paragraph, like this builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0)); Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType()); Assert.assertTrue(builder.isAtStartOfParagraph()); // A shorter way of moving the very start/end of a document is with these methods builder.moveToDocumentEnd(); Assert.assertTrue(builder.isAtEndOfParagraph()); builder.moveToDocumentStart(); Assert.assertTrue(builder.isAtStartOfParagraph());
moveToBookmark | |
public boolean moveToBookmark(java.lang.String bookmarkName, boolean isStart, boolean isAfter) throws java.lang.Exception |
Moves the cursor to a position before or after the bookmark start or end.
If desired position is not at inline level, moves to the next paragraph.
The comparison is not case-sensitive. If the bookmark was not found, false is returned and the cursor is not moved.
bookmarkName
- The name of the bookmark to move the cursor to.isStart
- When true, moves the cursor to the beginning of the bookmark.
When false, moves the cursor to the end of the bookmark.isAfter
- When true, moves the cursor to be after the bookmark
start or end position. When false, moves the cursor to be before the bookmark
start or end position.Example:
Shows how to move a cursor position to just after the bookmark end.Document doc = new Document(getMyDir() + "Bookmarks.docx"); DocumentBuilder builder = new DocumentBuilder(doc); // Move to after the end of the first bookmark Assert.assertTrue(builder.moveToBookmark("MyBookmark1", false, true)); builder.write(" Text appended via DocumentBuilder.");
moveToCell | |
public void moveToCell(int tableIndex, int rowIndex, int columnIndex, int characterIndex) |
The navigation is performed inside the current story of the current section.
For the index parameters, when index is greater than or equal to 0, it specifies an index from the beginning with 0 being the first element. When index is less than 0, it specified an index from the end with -1 being the last element.
tableIndex
- The index of the table to move to.rowIndex
- The index of the row in the table.columnIndex
- The index of the column in the table.characterIndex
- The index of the character inside the cell.
Currently can only specify 0 to move to the beginning of the cell or -1 to
move to the end of the cell.Example:
Shows how to move a cursor position to the specified table cell.Document doc = new Document(getMyDir() + "Tables.docx"); DocumentBuilder builder = new DocumentBuilder(doc); // Move the builder to row 3, cell 4 of the first table builder.moveToCell(0, 2, 3, 0); builder.write("\nCell contents added by DocumentBuilder");
moveToDocumentEnd | |
public void moveToDocumentEnd() |
Example:
Shows how to move a DocumentBuilder to different nodes in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start a bookmark and add content to it using a DocumentBuilder builder.startBookmark("MyBookmark"); builder.writeln("Bookmark contents."); builder.endBookmark("MyBookmark"); // The node that the DocumentBuilder is currently at is past the boundaries of the bookmark Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild()); // If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this builder.moveToBookmark("MyBookmark"); // Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild()); // We can move the builder to an individual node, // which in this case will be the first node of the first paragraph, like this builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0)); Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType()); Assert.assertTrue(builder.isAtStartOfParagraph()); // A shorter way of moving the very start/end of a document is with these methods builder.moveToDocumentEnd(); Assert.assertTrue(builder.isAtEndOfParagraph()); builder.moveToDocumentStart(); Assert.assertTrue(builder.isAtStartOfParagraph());
moveToDocumentStart | |
public void moveToDocumentStart() |
Example:
Shows how to move a DocumentBuilder to different nodes in a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start a bookmark and add content to it using a DocumentBuilder builder.startBookmark("MyBookmark"); builder.writeln("Bookmark contents."); builder.endBookmark("MyBookmark"); // The node that the DocumentBuilder is currently at is past the boundaries of the bookmark Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild()); // If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this builder.moveToBookmark("MyBookmark"); // Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild()); // We can move the builder to an individual node, // which in this case will be the first node of the first paragraph, like this builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0)); Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType()); Assert.assertTrue(builder.isAtStartOfParagraph()); // A shorter way of moving the very start/end of a document is with these methods builder.moveToDocumentEnd(); Assert.assertTrue(builder.isAtEndOfParagraph()); builder.moveToDocumentStart(); Assert.assertTrue(builder.isAtStartOfParagraph());
moveToField | |
public void moveToField(Field field, boolean isAfter) throws java.lang.Exception |
field
- The field to move the cursor to.isAfter
- When true, moves the cursor to be after the field end.
When false, moves the cursor to be before the field start. Example:
Shows how to move document builder's cursor to a specific field.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a field using the DocumentBuilder and add a run of text after it Field field = builder.insertField("MERGEFIELD field"); builder.write(" Text after the field."); // The builder's cursor is currently at end of the document Assert.assertNull(builder.getCurrentNode()); // We can move the builder to a field like this, placing the cursor at immediately after the field builder.moveToField(field, true); // Note that the cursor is at a place past the FieldEnd node of the field, meaning that we are not actually inside the field // If we wish to move the DocumentBuilder to inside a field, // we will need to move it to a field's FieldStart or FieldSeparator node using the DocumentBuilder.MoveTo() method Assert.assertEquals(field.getEnd(), builder.getCurrentNode().getPreviousSibling()); builder.write(" Text immediately after the field.");
moveToHeaderFooter | |
public void moveToHeaderFooter(int headerFooterType) |
After you moved the cursor into a header or footer, you can use the rest of DocumentBuilder methods to modify the contents of the header or footer.
If you want to create headers and footers different for the first page, you need
to set
If you want to create headers and footers different for even and odd pages, you need
to set
Use
headerFooterType
- A Example:
Shows how to create headers and footers in a document using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Specify that we want headers and footers different for first, even and odd pages builder.getPageSetup().setDifferentFirstPageHeaderFooter(true); builder.getPageSetup().setOddAndEvenPagesHeaderFooter(true); // Create the headers builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST); builder.write("Header for the first page"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_EVEN); builder.write("Header for even pages"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); builder.write("Header for all other pages"); // Create three pages in the document builder.moveToSection(0); builder.writeln("Page1"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page2"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page3"); doc.save(getArtifactsDir() + "DocumentBuilder.HeadersAndFooters.docx");
Example:
Shows how to a watermark image into a document using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // The best place for the watermark image is in the header or footer so it is shown on every page builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); BufferedImage image = ImageIO.read(new File(getImageDir() + "Transparent background logo.png")); // Insert a floating picture Shape shape = builder.insertImage(image); shape.setWrapType(WrapType.NONE); shape.setBehindText(true); shape.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); shape.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); // Calculate image left and top position so it appears in the center of the page shape.setLeft((builder.getPageSetup().getPageWidth() - shape.getWidth()) / 2.0); shape.setTop((builder.getPageSetup().getPageHeight() - shape.getHeight()) / 2.0); doc.save(getArtifactsDir() + "DocumentBuilder.InsertWatermark.docx");
moveToMergeField | |
public boolean moveToMergeField(java.lang.String fieldName) throws java.lang.Exception |
Note that this method deletes the merge field from the document after moving the cursor.
fieldName
- The case-insensitive name of the mail merge field.Example:
Shows how to insert checkbox form fields into a document during mail merge.public void insertCheckBox() throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.startTable(); builder.insertCell(); builder.insertField(" MERGEFIELD TableStart:StudentCourse "); builder.insertCell(); builder.insertField(" MERGEFIELD CourseName "); builder.insertCell(); builder.insertField(" MERGEFIELD TableEnd:StudentCourse "); builder.endTable(); // Add a handler for the MergeField event doc.getMailMerge().setFieldMergingCallback(new HandleMergeFieldInsertCheckBox()); // Execute mail merge with regions DataTable dataTable = getStudentCourseDataTable(); doc.getMailMerge().executeWithRegions(dataTable); // Save resulting document with a new name doc.save(getArtifactsDir() + "MailMergeEvent.InsertCheckBox.docx"); } private class HandleMergeFieldInsertCheckBox implements IFieldMergingCallback { /** * This is called for each merge field in the document * when Document.MailMerge.ExecuteWithRegions is called. */ public void fieldMerging(final FieldMergingArgs args) throws Exception { if (args.getDocumentFieldName().equals("CourseName")) { // The name of the table that we are merging can be found here Assert.assertEquals(args.getTableName(), "StudentCourse"); // Insert the checkbox for this merge field, using DocumentBuilder DocumentBuilder builder = new DocumentBuilder(args.getDocument()); builder.moveToMergeField(args.getFieldName()); builder.insertCheckBox(args.getDocumentFieldName() + Integer.toString(mCheckBoxCount), false, 0); // Get the actual value of the field String fieldValue = args.getFieldValue().toString(); // In this case, for every record index 'n', the corresponding field value is "Course n" Assert.assertEquals(args.getRecordIndex(), Character.getNumericValue(fieldValue.charAt(7))); builder.write(fieldValue); mCheckBoxCount++; } } public void imageFieldMerging(final ImageFieldMergingArgs args) { // Do nothing } /** * Counter for CheckBox name generation. */ private int mCheckBoxCount; } /** * Create DataTable and fill it with data. * In real life this DataTable should be filled from a database. */ private static DataTable getStudentCourseDataTable() throws Exception { DataTable dataTable = new DataTable("StudentCourse"); dataTable.getColumns().add("CourseName"); for (int i = 0; i < 10; i++) { DataRow datarow = dataTable.newRow(); dataTable.getRows().add(datarow); datarow.set(0, "Course " + Integer.toString(i)); } return dataTable; }
Example:
Shows how to fill MERGEFIELDs with data with a DocumentBuilder and without a mail merge.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert some MERGEFIELDS, which accept data from columns of the same name in a data source during a mail merge builder.insertField(" MERGEFIELD Chairman "); builder.insertField(" MERGEFIELD ChiefFinancialOfficer "); builder.insertField(" MERGEFIELD ChiefTechnologyOfficer "); // They can also be filled in manually like this builder.moveToMergeField("Chairman"); builder.setBold(true); builder.writeln("John Doe"); builder.moveToMergeField("ChiefFinancialOfficer"); builder.setItalic(true); builder.writeln("Jane Doe"); builder.moveToMergeField("ChiefTechnologyOfficer"); builder.setItalic(true); builder.writeln("John Bloggs"); doc.save(getArtifactsDir() + "DocumentBuilder.FillMergeFields.docx");
moveToMergeField | |
public boolean moveToMergeField(java.lang.String fieldName, boolean isAfter, boolean isDeleteField) throws java.lang.Exception |
fieldName
- The case-insensitive name of the mail merge field.isAfter
- When true, moves the cursor to be after the field end.
When false, moves the cursor to be before the field start. isDeleteField
- When true, deletes the merge field.Example:
Shows how to insert merge fields and move between them.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertField("MERGEFIELD MyMergeField1 \\* MERGEFORMAT"); builder.insertField("MERGEFIELD MyMergeField2 \\* MERGEFORMAT"); // The second merge field starts immediately after the end of the first // We'll move the builder's cursor to the end of the first so we can split them by text builder.moveToMergeField("MyMergeField1", true, false); Assert.assertEquals(doc.getRange().getFields().get(1).getStart(), builder.getCurrentNode()); builder.write(" Text between our two merge fields. "); doc.save(getArtifactsDir() + "DocumentBuilder.MergeFields.docx");
moveToParagraph | |
public void moveToParagraph(int paragraphIndex, int characterIndex) |
The navigation is performed inside the current story of the current section. That is, if you moved the cursor to the primary header of the first section, then paragraphIndex specified the index of the paragraph inside that header of that section.
When paragraphIndex is greater than or equal to 0, it specifies an index from the beginning of the section with 0 being the first paragraph. When paragraphIndex is less than 0, it specified an index from the end of the section with -1 being the last paragraph.
paragraphIndex
- The index of the paragraph to move to.characterIndex
- The index of the character inside the paragraph.
Currently can only specify 0 to move to the beginning of the paragraph or -1 to
move to the end of the paragraph.
Example:
Shows how to move a cursor position to the specified paragraph.// Open a document with a lot of paragraphs Document doc = new Document(getMyDir() + "Paragraphs.docx"); ParagraphCollection paragraphs = doc.getFirstSection().getBody().getParagraphs(); Assert.assertEquals(22, paragraphs.getCount()); // When we create a DocumentBuilder for a document, its cursor is at the very beginning of the document by default, // and any content added by the DocumentBuilder will just be prepended to the document DocumentBuilder builder = new DocumentBuilder(doc); Assert.assertEquals(0, paragraphs.indexOf(builder.getCurrentParagraph())); // We can manually move the DocumentBuilder to any paragraph in the document via a 0-based index like this builder.moveToParagraph(2, 0); builder.writeln("This is a new third paragraph. ");
moveToSection | |
public void moveToSection(int sectionIndex) |
When sectionIndex is greater than or equal to 0, it specifies an index from the beginning of the document with 0 being the first section. When sectionIndex is less than 0, it specified an index from the end of the document with -1 being the last section.
The cursor is moved to the first paragraph in the Body of the specified section.
sectionIndex
- The index of the section to move to.Example:
Shows how to create headers and footers in a document using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Specify that we want headers and footers different for first, even and odd pages builder.getPageSetup().setDifferentFirstPageHeaderFooter(true); builder.getPageSetup().setOddAndEvenPagesHeaderFooter(true); // Create the headers builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST); builder.write("Header for the first page"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_EVEN); builder.write("Header for even pages"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); builder.write("Header for all other pages"); // Create three pages in the document builder.moveToSection(0); builder.writeln("Page1"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page2"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page3"); doc.save(getArtifactsDir() + "DocumentBuilder.HeadersAndFooters.docx");
popFont | |
public void popFont() |
Example:
Shows how to use temporarily save and restore character formatting when building a document with DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Set up font formatting and write text that goes before the hyperlink builder.getFont().setName("Arial"); builder.getFont().setSize(24.0); builder.getFont().setBold(true); builder.write("To visit Google, hold Ctrl and click "); // Save the font formatting so we use different formatting for hyperlink and restore old formatting later builder.pushFont(); // Set new font formatting for the hyperlink and insert the hyperlink // The "Hyperlink" style is a Microsoft Word built-in style so we don't have to worry to // create it, it will be created automatically if it does not yet exist in the document builder.getFont().setStyleIdentifier(StyleIdentifier.HYPERLINK); builder.insertHyperlink("here", "http://www.google.com", false); // Restore the formatting that was before the hyperlink builder.popFont(); builder.write(". We hope you enjoyed the example."); doc.save(getArtifactsDir() + "DocumentBuilder.PushPopFont.docx");
pushFont | |
public void pushFont() |
Example:
Shows how to use temporarily save and restore character formatting when building a document with DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Set up font formatting and write text that goes before the hyperlink builder.getFont().setName("Arial"); builder.getFont().setSize(24.0); builder.getFont().setBold(true); builder.write("To visit Google, hold Ctrl and click "); // Save the font formatting so we use different formatting for hyperlink and restore old formatting later builder.pushFont(); // Set new font formatting for the hyperlink and insert the hyperlink // The "Hyperlink" style is a Microsoft Word built-in style so we don't have to worry to // create it, it will be created automatically if it does not yet exist in the document builder.getFont().setStyleIdentifier(StyleIdentifier.HYPERLINK); builder.insertHyperlink("here", "http://www.google.com", false); // Restore the formatting that was before the hyperlink builder.popFont(); builder.write(". We hope you enjoyed the example."); doc.save(getArtifactsDir() + "DocumentBuilder.PushPopFont.docx");
startBookmark | |
public BookmarkStart startBookmark(java.lang.String bookmarkName) |
Bookmarks in a document can overlap and span any range. To create a valid bookmark you need to
call both
Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.
bookmarkName
- Name of the bookmark.Example:
Shows how to insert a hyperlink referencing a local bookmark.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.startBookmark("Bookmark1"); builder.write("Bookmarked text."); builder.endBookmark("Bookmark1"); builder.writeln("Some other text"); // Specify font formatting for the hyperlink builder.getFont().setColor(Color.BLUE); builder.getFont().setUnderline(Underline.SINGLE); // Insert hyperlink // Switch \o is used to provide hyperlink tip text builder.insertHyperlink("Hyperlink Text", "Bookmark1\" \\o \"Hyperlink Tip", true); // Clear hyperlink formatting builder.getFont().clearFormatting(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertHyperlinkToLocalBookmark.docx");
Example:
Shows how to add some text into the document and encloses the text in a bookmark using DocumentBuilder.DocumentBuilder builder = new DocumentBuilder(); builder.startBookmark("MyBookmark"); builder.writeln("Text inside a bookmark."); builder.endBookmark("MyBookmark");
startEditableRange | |
public EditableRangeStart startEditableRange() |
Editable range in a document can overlap and span any range. To create a valid editable range you need to
call both
Badly formed editable range will be ignored when the document is saved.
Example:
Shows how to start and end an editable range.public void createEditableRanges() throws Exception { Document doc = new Document(getMyDir() + "Document.docx"); DocumentBuilder builder = new DocumentBuilder(doc); // Start an editable range EditableRangeStart edRange1Start = builder.startEditableRange(); // An EditableRange object is created for the EditableRangeStart that we just made EditableRange editableRange1 = edRange1Start.getEditableRange(); // Put something inside the editable range builder.writeln("Paragraph inside first editable range"); // An editable range is well-formed if it has a start and an end // Multiple editable ranges can be nested and overlapping EditableRangeEnd edRange1End = builder.endEditableRange(); // Explicitly state which EditableRangeStart a new EditableRangeEnd should be paired with EditableRangeStart edRange2Start = builder.startEditableRange(); builder.writeln("Paragraph inside second editable range"); EditableRange editableRange2 = edRange2Start.getEditableRange(); EditableRangeEnd edRange2End = builder.endEditableRange(edRange2Start); // Editable range starts and ends have their own respective node types Assert.assertEquals(edRange1Start.getNodeType(), NodeType.EDITABLE_RANGE_START); Assert.assertEquals(edRange1End.getNodeType(), NodeType.EDITABLE_RANGE_END); // Editable range IDs are unique and set automatically Assert.assertEquals(editableRange1.getId(), 0); Assert.assertEquals(editableRange2.getId(), 1); // Editable range starts and ends always belong to a range Assert.assertEquals(editableRange1.getEditableRangeStart(), edRange1Start); Assert.assertEquals(editableRange1.getEditableRangeEnd(), edRange1End); // They also inherit the ID of the entire editable range that they belong to Assert.assertEquals(editableRange1.getId(), edRange1Start.getId()); Assert.assertEquals(editableRange1.getId(), edRange1End.getId()); Assert.assertEquals(editableRange2.getId(), edRange2Start.getEditableRange().getId()); Assert.assertEquals(editableRange2.getId(), edRange2End.getEditableRangeStart().getEditableRange().getId()); // If the editable range was found in a document, it will probably have something in the single user property // But if we make one programmatically, the property is empty by default Assert.assertEquals(editableRange1.getSingleUser(), ""); // We have to set it ourselves if we want the ranges to belong to somebody editableRange1.setSingleUser("john.doe@myoffice.com"); editableRange2.setSingleUser("jane.doe@myoffice.com"); // Initialize a custom visitor for editable ranges that will print their contents EditableRangeInfoPrinter editableRangeReader = new EditableRangeInfoPrinter(); // Both the start and end of an editable range can accept visitors, but not the editable range itself edRange1Start.accept(editableRangeReader); edRange2End.accept(editableRangeReader); // Or, if we want to go over all the editable ranges in a document, we can get the document to accept the visitor editableRangeReader.reset(); doc.accept(editableRangeReader); System.out.println(editableRangeReader.toText()); } /// <summary> /// Visitor implementation that prints attributes and contents of ranges. /// </summary> public static class EditableRangeInfoPrinter extends DocumentVisitor { public EditableRangeInfoPrinter() { mBuilder = new StringBuilder(); } public String toText() { return mBuilder.toString(); } public void reset() { mBuilder = new StringBuilder(); mInsideEditableRange = false; } /// <summary> /// Called when an EditableRangeStart node is encountered in the document. /// </summary> public int visitEditableRangeStart(final EditableRangeStart editableRangeStart) { mBuilder.append(" -- Editable range found! -- " + "\r\n"); mBuilder.append("\tID: " + editableRangeStart.getId() + "\r\n"); mBuilder.append("\tUser: " + editableRangeStart.getEditableRange().getSingleUser() + "\r\n"); mBuilder.append("\tContents: " + "\r\n"); mInsideEditableRange = true; // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } /// <summary> /// Called when an EditableRangeEnd node is encountered in the document. /// </summary> public int visitEditableRangeEnd(final EditableRangeEnd editableRangeEnd) { mBuilder.append(" -- End of editable range -- " + "\r\n"); mInsideEditableRange = false; // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } /// <summary> /// Called when a Run node is encountered in the document. Only runs within editable ranges have their contents recorded. /// </summary> public int visitRun(final Run run) { if (mInsideEditableRange) { mBuilder.append("\t\"" + run.getText() + "\"" + "\r\n"); } // Let the visitor continue visiting other nodes return VisitorAction.CONTINUE; } private boolean mInsideEditableRange; private StringBuilder mBuilder; }
startTable | |
public Table startTable() |
The next method to call is
This method starts a nested table when called inside a cell.
Example:
Shows how to build a nice bordered table.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start building a table builder.startTable(); // Set the appropriate paragraph, cell, and row formatting. The formatting properties are preserved // until they are explicitly modified so there's no need to set them for each row or cell builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getCellFormat().clearFormatting(); builder.getCellFormat().setWidth(150.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN); builder.getCellFormat().setWrapText(false); builder.getCellFormat().setFitText(true); builder.getRowFormat().clearFormatting(); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getRowFormat().setHeight(50.0); builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D); builder.getRowFormat().getBorders().setColor(Color.ORANGE); builder.insertCell(); builder.write("Row 1, Col 1"); builder.insertCell(); builder.write("Row 1, Col 2"); builder.endRow(); // Remove the shading (clear background) builder.getCellFormat().getShading().clearFormatting(); builder.insertCell(); builder.write("Row 2, Col 1"); builder.insertCell(); builder.write("Row 2, Col 2"); builder.endRow(); builder.insertCell(); // Make the row height bigger so that a vertically oriented text could fit into cells builder.getRowFormat().setHeight(150.0); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("Row 3, Col 1"); builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("Row 3, Col 2"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertTable.docx");
Example:
Shows how to build a formatted table that contains 2 rows and 2 columns.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Insert a cell builder.insertCell(); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.write("This is row 1 cell 1"); // Use fixed column widths table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); // 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.0); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("This is row 2 cell 1"); // Insert a cell builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("This is row 2 cell 2"); builder.endRow(); builder.endTable();
Example:
Shows how to create a table that contains a single formatted cell.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.startTable(); builder.insertCell(); // Set the cell formatting CellFormat cellFormat = builder.getCellFormat(); cellFormat.setWidth(250.0); cellFormat.setLeftPadding(30.0); cellFormat.setRightPadding(30.0); cellFormat.setTopPadding(30.0); cellFormat.setBottomPadding(30.0); builder.write("Formatted cell"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.DocumentBuilderSetCellFormatting.docx");
write | |
public void write(java.lang.String text) |
text
- The string to insert into the document.Example:
Shows how to build a nice bordered table.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Start building a table builder.startTable(); // Set the appropriate paragraph, cell, and row formatting. The formatting properties are preserved // until they are explicitly modified so there's no need to set them for each row or cell builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER); builder.getCellFormat().clearFormatting(); builder.getCellFormat().setWidth(150.0); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.getCellFormat().getShading().setBackgroundPatternColor(Color.GREEN); builder.getCellFormat().setWrapText(false); builder.getCellFormat().setFitText(true); builder.getRowFormat().clearFormatting(); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getRowFormat().setHeight(50.0); builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D); builder.getRowFormat().getBorders().setColor(Color.ORANGE); builder.insertCell(); builder.write("Row 1, Col 1"); builder.insertCell(); builder.write("Row 1, Col 2"); builder.endRow(); // Remove the shading (clear background) builder.getCellFormat().getShading().clearFormatting(); builder.insertCell(); builder.write("Row 2, Col 1"); builder.insertCell(); builder.write("Row 2, Col 2"); builder.endRow(); builder.insertCell(); // Make the row height bigger so that a vertically oriented text could fit into cells builder.getRowFormat().setHeight(150.0); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("Row 3, Col 1"); builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("Row 3, Col 2"); builder.endRow(); builder.endTable(); doc.save(getArtifactsDir() + "DocumentBuilder.InsertTable.docx");
Example:
Shows how to build a formatted table that contains 2 rows and 2 columns.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Insert a cell builder.insertCell(); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.write("This is row 1 cell 1"); // Use fixed column widths table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); // 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.0); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("This is row 2 cell 1"); // Insert a cell builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("This is row 2 cell 2"); builder.endRow(); builder.endTable();
Example:
Shows how to create a simple table using DocumentBuilder with default formatting.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // We call this method to start building the table builder.startTable(); builder.insertCell(); builder.write("Row 1, Cell 1 Content."); // Build the second cell builder.insertCell(); builder.write("Row 1, Cell 2 Content."); // Call the following method to end the row and start a new row builder.endRow(); // Build the first cell of the second row builder.insertCell(); builder.write("Row 2, Cell 1 Content."); // Build the second cell. builder.insertCell(); builder.write("Row 2, Cell 2 Content."); builder.endRow(); // Signal that we have finished building the table builder.endTable(); // Save the document to disk doc.save(getArtifactsDir() + "DocumentBuilder.CreateSimpleTable.docx");
Example:
Shows how to insert a string surrounded by a border into a document.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.getFont().getBorder().setColor(Color.GREEN); builder.getFont().getBorder().setLineWidth(2.5); builder.getFont().getBorder().setLineStyle(LineStyle.DASH_DOT_STROKER); builder.write("Text surrounded by green border."); doc.save(getArtifactsDir() + "Border.FontBorder.docx");
writeln | |
public void writeln() |
Calls
Example:
Shows how to create headers and footers in a document using DocumentBuilder.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Specify that we want headers and footers different for first, even and odd pages builder.getPageSetup().setDifferentFirstPageHeaderFooter(true); builder.getPageSetup().setOddAndEvenPagesHeaderFooter(true); // Create the headers builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST); builder.write("Header for the first page"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_EVEN); builder.write("Header for even pages"); builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY); builder.write("Header for all other pages"); // Create three pages in the document builder.moveToSection(0); builder.writeln("Page1"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page2"); builder.insertBreak(BreakType.PAGE_BREAK); builder.writeln("Page3"); doc.save(getArtifactsDir() + "DocumentBuilder.HeadersAndFooters.docx");
writeln | |
public void writeln(java.lang.String text) |
text
- The string to insert into the document.Example:
Shows how to build a formatted table that contains 2 rows and 2 columns.Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Table table = builder.startTable(); // Insert a cell builder.insertCell(); builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); builder.write("This is row 1 cell 1"); // Use fixed column widths table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); // 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.0); builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); builder.getCellFormat().setOrientation(TextOrientation.UPWARD); builder.write("This is row 2 cell 1"); // Insert a cell builder.insertCell(); builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); builder.write("This is row 2 cell 2"); builder.endRow(); builder.endTable();