Aspose::Words::DocumentBuilder Class Reference

Detailed Description

Provides methods to insert text, images and other content, specify font, paragraph and section formatting.

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 Document.

The DocumentBuilder has an internal cursor where the text will be inserted when you call Write(), Writeln(), InsertBreak() and other methods. You can navigate the DocumentBuilder cursor to a different location in a document using various MoveToXXX methods.

Use the Font property to specify character formatting that will apply to all text inserted from the current position in the document onwards.

Use the ParagraphFormat property to specify paragraph formatting for the current and all paragraphs that will be inserted.

Use the PageSetup property to specify page and section properties for the current section and all section that will be inserted.

Use the CellFormat and RowFormat properties to specify formatting properties for table cells and rows. User the InsertCell and EndRow methods to build a table.

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.

Examples

Shows how to create headers and footers in a document using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Specify that we want different headers and footers for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers, then add three pages to the document to display each header type.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header for the first page");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header for even pages");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header for all other pages");
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page3");
doc->Save(ArtifactsDir + u"DocumentBuilder.HeadersAndFooters.docx");

Shows how to build a table with custom borders.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->ClearFormatting();
builder->get_CellFormat()->set_Width(150);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_GreenYellow());
builder->get_CellFormat()->set_WrapText(false);
builder->get_CellFormat()->set_FitText(true);
builder->get_RowFormat()->ClearFormatting();
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_RowFormat()->set_Height(50);
builder->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::Engrave3D);
builder->get_RowFormat()->get_Borders()->set_Color(System::Drawing::Color::get_Orange());
builder->InsertCell();
builder->Write(u"Row 1, Col 1");
builder->InsertCell();
builder->Write(u"Row 1, Col 2");
builder->EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder->get_CellFormat()->get_Shading()->ClearFormatting();
builder->InsertCell();
builder->Write(u"Row 2, Col 1");
builder->InsertCell();
builder->Write(u"Row 2, Col 2");
builder->EndRow();
// Increase row height to fit the vertical text.
builder->InsertCell();
builder->get_RowFormat()->set_Height(150);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 3, Col 1");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 3, Col 2");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTable.docx");

Shows how to use a document builder to create a table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Start the table, then populate the first row with two cells.
builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, Cell 2.");
// Call the builder's "EndRow" method to start a new row.
builder->EndRow();
builder->InsertCell();
builder->Write(u"Row 2, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 2, Cell 2.");
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.CreateTable.docx");

#include <Aspose.Words.Cpp/DocumentBuilder.h>

+ Inheritance diagram for Aspose::Words::DocumentBuilder:

Public Member Functions

 DocumentBuilder ()
 Initializes a new instance of this class. More...
 
 DocumentBuilder (const SharedPtr< Document > &doc)
 Initializes a new instance of this class. More...
 
SharedPtr< RowDeleteRow (int32_t tableIndex, int32_t rowIndex)
 Deletes a row from a table. More...
 
SharedPtr< BookmarkEndEndBookmark (const String &bookmarkName)
 Marks the current position in the document as a bookmark end. More...
 
SharedPtr< BookmarkEndEndColumnBookmark (const String &bookmarkName)
 Marks the current position in the document as a column bookmark end. The position must be in a table cell. More...
 
SharedPtr< EditableRangeEndEndEditableRange ()
 Marks the current position in the document as an editable range end. More...
 
SharedPtr< EditableRangeEndEndEditableRange (const SharedPtr< EditableRangeStart > &start)
 Marks the current position in the document as an editable range end. More...
 
SharedPtr< RowEndRow ()
 Ends a table row in the document. More...
 
SharedPtr< TableEndTable ()
 Ends a table in the document. More...
 
bool get_Bold ()
 True if the font is formatted as bold. More...
 
SharedPtr< CellFormatget_CellFormat ()
 Returns an object that represents current table cell formatting properties. More...
 
SharedPtr< Nodeget_CurrentNode ()
 Gets the node that is currently selected in this DocumentBuilder. More...
 
SharedPtr< Paragraphget_CurrentParagraph ()
 Gets the paragraph that is currently selected in this DocumentBuilder. More...
 
SharedPtr< Sectionget_CurrentSection ()
 Gets the section that is currently selected in this DocumentBuilder. More...
 
SharedPtr< Storyget_CurrentStory ()
 Gets the story that is currently selected in this DocumentBuilder. More...
 
SharedPtr< Documentget_Document () const
 Gets or sets the Document object that this object is attached to. More...
 
SharedPtr< Fontget_Font ()
 Returns an object that represents current font formatting properties. More...
 
bool get_IsAtEndOfParagraph ()
 Returns true if the cursor is at the end of the current paragraph. More...
 
bool get_IsAtStartOfParagraph ()
 Returns true if the cursor is at the beginning of the current paragraph (no text before the cursor). More...
 
bool get_Italic ()
 True if the font is formatted as italic. More...
 
SharedPtr< ListFormatget_ListFormat ()
 Returns an object that represents current list formatting properties. More...
 
SharedPtr< PageSetupget_PageSetup ()
 Returns an object that represents current page setup and section properties. More...
 
SharedPtr< ParagraphFormatget_ParagraphFormat ()
 Returns an object that represents current paragraph formatting properties. More...
 
SharedPtr< RowFormatget_RowFormat ()
 Returns an object that represents current table row formatting properties. More...
 
Underline get_Underline ()
 Gets/sets underline type for the current font. More...
 
virtual const TypeInfoGetType () const override
 
void InsertBreak (BreakType breakType)
 Inserts a break of the specified type into the document. More...
 
SharedPtr< CellInsertCell ()
 Inserts a table cell into the document. More...
 
SharedPtr< ShapeInsertChart (ChartType chartType, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 Inserts an chart object into the document and scales it to the specified size. More...
 
SharedPtr< ShapeInsertChart (ChartType chartType, double width, double height)
 Inserts an chart object into the document and scales it to the specified size. More...
 
SharedPtr< FormFieldInsertCheckBox (const String &name, bool checkedValue, int32_t size)
 Inserts a checkbox form field at the current position. More...
 
SharedPtr< FormFieldInsertCheckBox (const String &name, bool defaultValue, bool checkedValue, int32_t size)
 Inserts a checkbox form field at the current position. More...
 
SharedPtr< FormFieldInsertComboBox (const String &name, const ArrayPtr< String > &items, int32_t selectedIndex)
 Inserts a combobox form field at the current position. More...
 
SharedPtr< NodeInsertDocument (const SharedPtr< Document > &srcDoc, ImportFormatMode importFormatMode)
 Inserts a document at the cursor position. More...
 
SharedPtr< NodeInsertDocument (const SharedPtr< Document > &srcDoc, ImportFormatMode importFormatMode, const SharedPtr< ImportFormatOptions > &importFormatOptions)
 Inserts a document at the cursor position. More...
 
SharedPtr< FieldInsertField (FieldType fieldType, bool updateField)
 Inserts a Word field into a document and optionally updates the field result. More...
 
SharedPtr< FieldInsertField (const String &fieldCode)
 Inserts a Word field into a document and updates the field result. More...
 
SharedPtr< FieldInsertField (const String &fieldCode, const String &fieldValue)
 Inserts a Word field into a document without updating the field result. More...
 
SharedPtr< FootnoteInsertFootnote (FootnoteType footnoteType, const String &footnoteText)
 Inserts a footnote or endnote into the document. More...
 
SharedPtr< FootnoteInsertFootnote (FootnoteType footnoteType, const String &footnoteText, const String &referenceMark)
 Inserts a footnote or endnote into the document. More...
 
SharedPtr< ShapeInsertHorizontalRule ()
 Inserts a horizontal rule shape into the document. More...
 
void InsertHtml (const String &html)
 Inserts an HTML string into the document. More...
 
void InsertHtml (const String &html, HtmlInsertOptions options)
 Inserts an HTML string into the document. Allows to specify additional options. More...
 
void InsertHtml (const String &html, bool useBuilderFormatting)
 Inserts an HTML string into the document. More...
 
SharedPtr< FieldInsertHyperlink (const String &displayText, const String &urlOrBookmark, bool isBookmark)
 Inserts a hyperlink into the document. More...
 
SharedPtr< ShapeInsertImage (const ArrayPtr< uint8_t > &imageBytes)
 Inserts an image from a byte array into the document. The image is inserted inline and at 100% scale. More...
 
SharedPtr< ShapeInsertImage (const ArrayPtr< uint8_t > &imageBytes, double width, double height)
 Inserts an inline image from a byte array into the document and scales it to the specified size. More...
 
SharedPtr< ShapeInsertImage (const SharedPtr< Image > &image)
 Inserts an image from a Image object into the document. The image is inserted inline and at 100% scale. More...
 
SharedPtr< ShapeInsertImage (const SharedPtr< Image > &image, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 Inserts an image from a Image object at the specified position and size. More...
 
SharedPtr< ShapeInsertImage (const SharedPtr< Image > &image, double width, double height)
 Inserts an inline image from a Image object into the document and scales it to the specified size. More...
 
SharedPtr< ShapeInsertImage (const SharedPtr< Stream > &stream)
 Inserts an image from a stream into the document. The image is inserted inline and at 100% scale. More...
 
SharedPtr< ShapeInsertImage (const SharedPtr< Stream > &stream, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 Inserts an image from a stream at the specified position and size. More...
 
SharedPtr< ShapeInsertImage (const SharedPtr< Stream > &stream, double width, double height)
 Inserts an inline image from a stream into the document and scales it to the specified size. More...
 
SharedPtr< ShapeInsertImage (const String &fileName)
 Inserts an image from a file or URL into the document. The image is inserted inline and at 100% scale. More...
 
SharedPtr< ShapeInsertImage (const String &fileName, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 Inserts an image from a file or URL at the specified position and size. More...
 
SharedPtr< ShapeInsertImage (const 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. More...
 
template<typename CharType , typename Traits >
SharedPtr< ShapeInsertImage (std::basic_istream< CharType, Traits > &stream)
 
template<typename CharType , typename Traits >
SharedPtr< ShapeInsertImage (std::basic_istream< CharType, Traits > &stream, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 
template<typename CharType , typename Traits >
SharedPtr< ShapeInsertImage (std::basic_istream< CharType, Traits > &stream, double width, double height)
 
SharedPtr< ShapeInsertImage (ArrayPtr< uint8_t > imageBytes, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 Inserts an image from a byte array at the specified position and size. More...
 
void InsertNode (const SharedPtr< Node > &node)
 Inserts a text level node inside the current paragraph before the cursor. More...
 
SharedPtr< ShapeInsertOleObject (const SharedPtr< Stream > &stream, const String &progId, bool asIcon, const SharedPtr< Stream > &presentation)
 Inserts an embedded OLE object from a stream into the document. More...
 
SharedPtr< ShapeInsertOleObject (const String &fileName, bool isLinked, bool asIcon, const SharedPtr< Stream > &presentation)
 Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using file extension. More...
 
SharedPtr< ShapeInsertOleObject (const String &fileName, const String &progId, bool isLinked, bool asIcon, const SharedPtr< Stream > &presentation)
 Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using given progID parameter. More...
 
template<typename CharType , typename Traits >
SharedPtr< ShapeInsertOleObject (std::basic_istream< CharType, Traits > &stream, String progId, bool asIcon, std::basic_istream< CharType, Traits > &presentation)
 
template<typename CharType , typename Traits >
SharedPtr< ShapeInsertOleObject (String fileName, bool isLinked, bool asIcon, std::basic_istream< CharType, Traits > &presentation)
 
template<typename CharType , typename Traits >
SharedPtr< ShapeInsertOleObject (String fileName, String progId, bool isLinked, bool asIcon, std::basic_istream< CharType, Traits > &presentation)
 
SharedPtr< ShapeInsertOleObjectAsIcon (const SharedPtr< Stream > &stream, const String &progId, const String &iconFile, const String &iconCaption)
 Inserts an embedded OLE object as icon from a stream into the document. Allows to specify icon file and caption. Detects OLE object type using given progID parameter. More...
 
SharedPtr< ShapeInsertOleObjectAsIcon (const String &fileName, bool isLinked, const String &iconFile, const 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. More...
 
SharedPtr< ShapeInsertOleObjectAsIcon (const String &fileName, const String &progId, bool isLinked, const String &iconFile, const 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 given progID parameter. More...
 
template<typename CharType , typename Traits >
SharedPtr< ShapeInsertOleObjectAsIcon (std::basic_istream< CharType, Traits > &stream, String progId, String iconFile, String iconCaption)
 
SharedPtr< ShapeInsertOnlineVideo (const String &videoUrl, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 Inserts an online video object into the document and scales it to the specified size. More...
 
SharedPtr< ShapeInsertOnlineVideo (const String &videoUrl, const String &videoEmbedCode, const ArrayPtr< uint8_t > &thumbnailImageBytes, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 Inserts an online video object into the document and scales it to the specified size. More...
 
SharedPtr< ShapeInsertOnlineVideo (const String &videoUrl, const String &videoEmbedCode, const ArrayPtr< uint8_t > &thumbnailImageBytes, double width, double height)
 Inserts an online video object into the document and scales it to the specified size. More...
 
SharedPtr< ShapeInsertOnlineVideo (const String &videoUrl, double width, double height)
 Inserts an online video object into the document and scales it to the specified size. More...
 
SharedPtr< ParagraphInsertParagraph ()
 Inserts a paragraph break into the document. More...
 
SharedPtr< ShapeInsertShape (ShapeType shapeType, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, double width, double height, WrapType wrapType)
 Inserts free-floating shape with specified position, size and text wrap type. More...
 
SharedPtr< ShapeInsertShape (ShapeType shapeType, double width, double height)
 Inserts inline shape with specified type and size. More...
 
SharedPtr< ShapeInsertSignatureLine (const SharedPtr< SignatureLineOptions > &signatureLineOptions)
 Inserts a signature line at the current position. More...
 
SharedPtr< ShapeInsertSignatureLine (const SharedPtr< SignatureLineOptions > &signatureLineOptions, RelativeHorizontalPosition horzPos, double left, RelativeVerticalPosition vertPos, double top, WrapType wrapType)
 Inserts a signature line at the specified position. More...
 
void InsertStyleSeparator ()
 Inserts style separator into the document. More...
 
SharedPtr< FieldInsertTableOfContents (const String &switches)
 Inserts a TOC (table of contents) field into the document. More...
 
SharedPtr< FormFieldInsertTextInput (const String &name, TextFormFieldType type, const String &format, const String &fieldValue, int32_t maxLength)
 Inserts a text form field at the current position. More...
 
virtual bool Is (const TypeInfo &target) const override
 
void MoveTo (const SharedPtr< Node > &node)
 Moves the cursor to an inline node or to the end of a paragraph. More...
 
bool MoveToBookmark (const String &bookmarkName)
 Moves the cursor to a bookmark. More...
 
bool MoveToBookmark (const String &bookmarkName, bool isStart, bool isAfter)
 Moves the cursor to a bookmark with greater precision. More...
 
void MoveToCell (int32_t tableIndex, int32_t rowIndex, int32_t columnIndex, int32_t characterIndex)
 Moves the cursor to a table cell in the current section. More...
 
void MoveToDocumentEnd ()
 Moves the cursor to the end of the document. More...
 
void MoveToDocumentStart ()
 Moves the cursor to the beginning of the document. More...
 
void MoveToField (const SharedPtr< Field > &field, bool isAfter)
 Moves the cursor to a field in the document. More...
 
void MoveToHeaderFooter (HeaderFooterType headerFooterType)
 Moves the cursor to the beginning of a header or footer in the current section. More...
 
bool MoveToMergeField (const String &fieldName)
 Moves the cursor to a position just beyond the specified merge field and removes the merge field. More...
 
bool MoveToMergeField (const String &fieldName, bool isAfter, bool isDeleteField)
 Moves the merge field to the specified merge field. More...
 
void MoveToParagraph (int32_t paragraphIndex, int32_t characterIndex)
 Moves the cursor to a paragraph in the current section. More...
 
void MoveToSection (int32_t sectionIndex)
 Moves the cursor to the beginning of the body in a specified section. More...
 
void PopFont ()
 Retrieves character formatting previously saved on the stack. More...
 
void PushFont ()
 Saves current character formatting onto the stack. More...
 
void set_Bold (bool value)
 Setter for get_Bold. More...
 
void set_Document (const SharedPtr< Document > &value)
 Setter for get_Document. More...
 
void set_Italic (bool value)
 Setter for get_Italic. More...
 
void set_Underline (Underline value)
 Setter for get_Underline. More...
 
SharedPtr< BookmarkStartStartBookmark (const String &bookmarkName)
 Marks the current position in the document as a bookmark start. More...
 
SharedPtr< BookmarkStartStartColumnBookmark (const String &bookmarkName)
 Marks the current position in the document as a column bookmark start. The position must be in a table cell. More...
 
SharedPtr< EditableRangeStartStartEditableRange ()
 Marks the current position in the document as an editable range start. More...
 
SharedPtr< TableStartTable ()
 Starts a table in the document. More...
 
void Write (const String &text)
 Inserts a string into the document at the current insert position. More...
 
void Writeln ()
 Inserts a paragraph break into the document. More...
 
void Writeln (const String &text)
 Inserts a string and a paragraph break into the document. More...
 

Static Public Member Functions

static const TypeInfoType ()
 

Constructor & Destructor Documentation

◆ DocumentBuilder() [1/2]

Aspose::Words::DocumentBuilder::DocumentBuilder ( )

Initializes a new instance of this class.

◆ DocumentBuilder() [2/2]

Aspose::Words::DocumentBuilder::DocumentBuilder ( const System::SharedPtr< Aspose::Words::Document > &  doc)

Initializes a new instance of this class.

Parameters
docThe Document object to attach to.
Examples

Shows how to insert formatted text using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Specify font formatting, then add text.
SharedPtr<Aspose::Words::Font> font = builder->get_Font();
font->set_Size(16);
font->set_Bold(true);
font->set_Name(u"Courier New");
font->set_Underline(Underline::Dash);
builder->Write(u"Hello world!");

Shows how to create headers and footers in a document using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Specify that we want different headers and footers for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers, then add three pages to the document to display each header type.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header for the first page");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header for even pages");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header for all other pages");
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page3");
doc->Save(ArtifactsDir + u"DocumentBuilder.HeadersAndFooters.docx");

Shows how to insert a Table of contents (TOC) into a document using heading styles as entries.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a table of contents for the first page of the document.
// Configure the table to pick up paragraphs with headings of levels 1 to 3.
// Also, set its entries to be hyperlinks that will take us
// to the location of the heading when left-clicked in Microsoft Word.
builder->InsertTableOfContents(u"\\o \"1-3\" \\h \\z \\u");
builder->InsertBreak(BreakType::PageBreak);
// Populate the table of contents by adding paragraphs with heading styles.
// Each such heading with a level between 1 and 3 will create an entry in the table.
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 1.1");
builder->Writeln(u"Heading 1.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 2");
builder->Writeln(u"Heading 3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading3);
builder->Writeln(u"Heading 3.1.1");
builder->Writeln(u"Heading 3.1.2");
builder->Writeln(u"Heading 3.1.3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading4);
builder->Writeln(u"Heading 3.1.3.1");
builder->Writeln(u"Heading 3.1.3.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.2");
builder->Writeln(u"Heading 3.3");
// A table of contents is a field of a type that needs to be updated to show an up-to-date result.
doc->UpdateFields();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertToc.docx");

Member Function Documentation

◆ DeleteRow()

System::SharedPtr<Aspose::Words::Tables::Row> Aspose::Words::DocumentBuilder::DeleteRow ( int32_t  tableIndex,
int32_t  rowIndex 
)

Deletes a row from a table.

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.

Parameters
tableIndexThe index of the table.
rowIndexThe index of the row in the table.
Returns
The row node that was just removed.
Examples

Shows how to delete a row from a table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
builder->InsertCell();
builder->Write(u"Row 2, cell 1.");
builder->InsertCell();
builder->Write(u"Row 2, cell 2.");
builder->EndTable();
ASSERT_EQ(2, table->get_Rows()->get_Count());
// Delete the first row of the first table in the document.
builder->DeleteRow(0, 0);
ASSERT_EQ(1, table->get_Rows()->get_Count());
ASSERT_EQ(u"Row 2, cell 1.\aRow 2, cell 2.\a\a", table->GetText().Trim());

◆ EndBookmark()

System::SharedPtr<Aspose::Words::BookmarkEnd> Aspose::Words::DocumentBuilder::EndBookmark ( const System::String bookmarkName)

Marks the current position in the document as a bookmark end.

Bookmarks in a document can overlap and span any range. To create a valid bookmark you need to call both StartBookmark() and EndBookmark() with the same bookmarkName parameter.

Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.

Parameters
bookmarkNameName of the bookmark.
Returns
The bookmark end node that was just created.
Examples

Shows how create a bookmark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// A valid bookmark needs to have document body text enclosed by
// BookmarkStart and BookmarkEnd nodes created with a matching bookmark name.
builder->StartBookmark(u"MyBookmark");
builder->Writeln(u"Hello world!");
builder->EndBookmark(u"MyBookmark");
ASSERT_EQ(1, doc->get_Range()->get_Bookmarks()->get_Count());
ASSERT_EQ(u"MyBookmark", doc->get_Range()->get_Bookmarks()->idx_get(0)->get_Name());
ASSERT_EQ(u"Hello world!", doc->get_Range()->get_Bookmarks()->idx_get(0)->get_Text().Trim());

Shows how to insert a hyperlink which references a local bookmark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartBookmark(u"Bookmark1");
builder->Write(u"Bookmarked text. ");
builder->EndBookmark(u"Bookmark1");
builder->Writeln(u"Text outside of the bookmark.");
// Insert a HYPERLINK field that links to the bookmark. We can pass field switches
// to the "InsertHyperlink" method as part of the argument containing the referenced bookmark's name.
builder->get_Font()->set_Color(System::Drawing::Color::get_Blue());
builder->get_Font()->set_Underline(Underline::Single);
builder->InsertHyperlink(u"Link to Bookmark1", u"Bookmark1\" \\o \"Hyperlink Tip", true);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertHyperlinkToLocalBookmark.docx");

◆ EndColumnBookmark()

System::SharedPtr<Aspose::Words::BookmarkEnd> Aspose::Words::DocumentBuilder::EndColumnBookmark ( const System::String bookmarkName)

Marks the current position in the document as a column bookmark end. The position must be in a table cell.

A column bookmark covers one or more columns in a range of rows. To create a valid bookmark you need to call both StartColumnBookmark() and EndColumnBookmark() with the same bookmarkName parameter.

Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.

The actual position of the inserted BookmarkEnd node may differ from the current document builder position.

Parameters
bookmarkNameName of the bookmark.
Returns
The bookmark end node that was just created.
Examples

Shows how to create a column bookmark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
builder->InsertCell();
// Cells 1,2,4,5 will be bookmarked.
builder->StartColumnBookmark(u"MyBookmark_1");
// Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.
builder->StartColumnBookmark(u"MyBookmark_1");
builder->StartColumnBookmark(u"BadStartBookmark");
builder->Write(u"Cell 1");
builder->InsertCell();
builder->Write(u"Cell 2");
builder->InsertCell();
builder->Write(u"Cell 3");
builder->EndRow();
builder->InsertCell();
builder->Write(u"Cell 4");
builder->InsertCell();
builder->Write(u"Cell 5");
builder->EndColumnBookmark(u"MyBookmark_1");
builder->EndColumnBookmark(u"MyBookmark_1");
builder->InsertCell();
builder->Write(u"Cell 6");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"Bookmarks.CreateColumnBookmark.docx");

◆ EndEditableRange() [1/2]

System::SharedPtr<Aspose::Words::EditableRangeEnd> Aspose::Words::DocumentBuilder::EndEditableRange ( )

Marks the current position in the document as an editable range end.

Editable range in a document can overlap and span any range. To create a valid editable range you need to call both StartEditableRange and EndEditableRange or EndEditableRange() methods.

Badly formed editable range will be ignored when the document is saved.

Returns
The editable range end node that was just created.
Examples

Shows how to work with an editable range.

auto doc = MakeObject<Document>();
doc->Protect(ProtectionType::ReadOnly, u"MyPassword");
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(String(u"Hello world! Since we have set the document's protection level to read-only,") +
u" we cannot edit this paragraph without the password.");
// Editable ranges allow us to leave parts of protected documents open for editing.
SharedPtr<EditableRangeStart> editableRangeStart = builder->StartEditableRange();
builder->Writeln(u"This paragraph is inside an editable range, and can be edited.");
SharedPtr<EditableRangeEnd> editableRangeEnd = builder->EndEditableRange();
// A well-formed editable range has a start node, and end node.
// These nodes have matching IDs and encompass editable nodes.
SharedPtr<EditableRange> editableRange = editableRangeStart->get_EditableRange();
ASSERT_EQ(editableRangeStart->get_Id(), editableRange->get_Id());
ASSERT_EQ(editableRangeEnd->get_Id(), editableRange->get_Id());
// Different parts of the editable range link to each other.
ASSERT_EQ(editableRangeStart->get_Id(), editableRange->get_EditableRangeStart()->get_Id());
ASSERT_EQ(editableRangeStart->get_Id(), editableRangeEnd->get_EditableRangeStart()->get_Id());
ASSERT_EQ(editableRange->get_Id(), editableRangeStart->get_EditableRange()->get_Id());
ASSERT_EQ(editableRangeEnd->get_Id(), editableRange->get_EditableRangeEnd()->get_Id());
// We can access the node types of each part like this. The editable range itself is not a node,
// but an entity which consists of a start, an end, and their enclosed contents.
ASSERT_EQ(NodeType::EditableRangeStart, editableRangeStart->get_NodeType());
ASSERT_EQ(NodeType::EditableRangeEnd, editableRangeEnd->get_NodeType());
builder->Writeln(u"This paragraph is outside the editable range, and cannot be edited.");
doc->Save(ArtifactsDir + u"EditableRange.CreateAndRemove.docx");
// Remove an editable range. All the nodes that were inside the range will remain intact.
editableRange->Remove();

◆ EndEditableRange() [2/2]

System::SharedPtr<Aspose::Words::EditableRangeEnd> Aspose::Words::DocumentBuilder::EndEditableRange ( const System::SharedPtr< Aspose::Words::EditableRangeStart > &  start)

Marks the current position in the document as an editable range end.

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 StartEditableRange and EndEditableRange or EndEditableRange() methods.

Badly formed editable range will be ignored when the document is saved.

Parameters
startThis editable range start.
Returns
The editable range end node that was just created.
Examples

Shows how to create nested editable ranges.

auto doc = MakeObject<Document>();
doc->Protect(ProtectionType::ReadOnly, u"MyPassword");
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(String(u"Hello world! Since we have set the document's protection level to read-only, ") +
u"we cannot edit this paragraph without the password.");
// Create two nested editable ranges.
SharedPtr<EditableRangeStart> outerEditableRangeStart = builder->StartEditableRange();
builder->Writeln(u"This paragraph inside the outer editable range and can be edited.");
SharedPtr<EditableRangeStart> innerEditableRangeStart = builder->StartEditableRange();
builder->Writeln(u"This paragraph inside both the outer and inner editable ranges and can be edited.");
// Currently, the document builder's node insertion cursor is in more than one ongoing editable range.
// When we want to end an editable range in this situation,
// we need to specify which of the ranges we wish to end by passing its EditableRangeStart node.
builder->EndEditableRange(innerEditableRangeStart);
builder->Writeln(u"This paragraph inside the outer editable range and can be edited.");
builder->EndEditableRange(outerEditableRangeStart);
builder->Writeln(u"This paragraph is outside any editable ranges, and cannot be edited.");
// If a region of text has two overlapping editable ranges with specified groups,
// the combined group of users excluded by both groups are prevented from editing it.
outerEditableRangeStart->get_EditableRange()->set_EditorGroup(EditorType::Everyone);
innerEditableRangeStart->get_EditableRange()->set_EditorGroup(EditorType::Contributors);
doc->Save(ArtifactsDir + u"EditableRange.Nested.docx");

◆ EndRow()

System::SharedPtr<Aspose::Words::Tables::Row> Aspose::Words::DocumentBuilder::EndRow ( )

Ends a table row in the document.

Call EndRow to end a table row. If you call InsertCell immediately after that, then the table continues on a new row.

Use the RowFormat property to specify row formatting.

Returns
The row node that was just finished.
Examples

Shows how to merge table cells vertically.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a cell into the first column of the first row.
// This cell will be the first in a range of vertically merged cells.
builder->InsertCell();
builder->get_CellFormat()->set_VerticalMerge(CellMerge::First);
builder->Write(u"Text in merged cells.");
// Insert a cell into the second column of the first row, then end the row.
// Also, configure the builder to disable vertical merging in created cells.
builder->InsertCell();
builder->get_CellFormat()->set_VerticalMerge(CellMerge::None);
builder->Write(u"Text in unmerged cell.");
builder->EndRow();
// Insert a cell into the first column of the second row.
// Instead of adding text contents, we will merge this cell with the first cell that we added directly above.
builder->InsertCell();
builder->get_CellFormat()->set_VerticalMerge(CellMerge::Previous);
// Insert another independent cell in the second column of the second row.
builder->InsertCell();
builder->get_CellFormat()->set_VerticalMerge(CellMerge::None);
builder->Write(u"Text in unmerged cell.");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"CellFormat.VerticalMerge.docx");

Shows how to build a table with custom borders.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->ClearFormatting();
builder->get_CellFormat()->set_Width(150);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_GreenYellow());
builder->get_CellFormat()->set_WrapText(false);
builder->get_CellFormat()->set_FitText(true);
builder->get_RowFormat()->ClearFormatting();
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_RowFormat()->set_Height(50);
builder->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::Engrave3D);
builder->get_RowFormat()->get_Borders()->set_Color(System::Drawing::Color::get_Orange());
builder->InsertCell();
builder->Write(u"Row 1, Col 1");
builder->InsertCell();
builder->Write(u"Row 1, Col 2");
builder->EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder->get_CellFormat()->get_Shading()->ClearFormatting();
builder->InsertCell();
builder->Write(u"Row 2, Col 1");
builder->InsertCell();
builder->Write(u"Row 2, Col 2");
builder->EndRow();
// Increase row height to fit the vertical text.
builder->InsertCell();
builder->get_RowFormat()->set_Height(150);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 3, Col 1");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 3, Col 2");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTable.docx");

Shows how to build a formatted 2x2 table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"Row 1, cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
// While building the table, the document builder will apply its current RowFormat/CellFormat property values
// to the current row/cell that its cursor is in and any new rows/cells as it creates them.
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(0)->get_CellFormat()->get_VerticalAlignment());
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(1)->get_CellFormat()->get_VerticalAlignment());
builder->InsertCell();
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 2, cell 1.");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 2, cell 2.");
builder->EndRow();
builder->EndTable();
// Previously added rows and cells are not retroactively affected by changes to the builder's formatting.
ASPOSE_ASSERT_EQ(0, table->get_Rows()->idx_get(0)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Auto, table->get_Rows()->idx_get(0)->get_RowFormat()->get_HeightRule());
ASPOSE_ASSERT_EQ(100, table->get_Rows()->idx_get(1)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Exactly, table->get_Rows()->idx_get(1)->get_RowFormat()->get_HeightRule());
ASSERT_EQ(TextOrientation::Upward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(0)->get_CellFormat()->get_Orientation());
ASSERT_EQ(TextOrientation::Downward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(1)->get_CellFormat()->get_Orientation());
doc->Save(ArtifactsDir + u"DocumentBuilder.BuildTable.docx");

◆ EndTable()

System::SharedPtr<Aspose::Words::Tables::Table> Aspose::Words::DocumentBuilder::EndTable ( )

Ends a table in the document.

This method should be called only once after EndRow was called. When called, EndTable moves the cursor out of the current cell to point just after the table.

Returns
The table node that was just finished.
Examples

Shows how to build a table with custom borders.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->ClearFormatting();
builder->get_CellFormat()->set_Width(150);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_GreenYellow());
builder->get_CellFormat()->set_WrapText(false);
builder->get_CellFormat()->set_FitText(true);
builder->get_RowFormat()->ClearFormatting();
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_RowFormat()->set_Height(50);
builder->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::Engrave3D);
builder->get_RowFormat()->get_Borders()->set_Color(System::Drawing::Color::get_Orange());
builder->InsertCell();
builder->Write(u"Row 1, Col 1");
builder->InsertCell();
builder->Write(u"Row 1, Col 2");
builder->EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder->get_CellFormat()->get_Shading()->ClearFormatting();
builder->InsertCell();
builder->Write(u"Row 2, Col 1");
builder->InsertCell();
builder->Write(u"Row 2, Col 2");
builder->EndRow();
// Increase row height to fit the vertical text.
builder->InsertCell();
builder->get_RowFormat()->set_Height(150);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 3, Col 1");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 3, Col 2");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTable.docx");

Shows how to build a formatted 2x2 table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"Row 1, cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
// While building the table, the document builder will apply its current RowFormat/CellFormat property values
// to the current row/cell that its cursor is in and any new rows/cells as it creates them.
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(0)->get_CellFormat()->get_VerticalAlignment());
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(1)->get_CellFormat()->get_VerticalAlignment());
builder->InsertCell();
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 2, cell 1.");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 2, cell 2.");
builder->EndRow();
builder->EndTable();
// Previously added rows and cells are not retroactively affected by changes to the builder's formatting.
ASPOSE_ASSERT_EQ(0, table->get_Rows()->idx_get(0)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Auto, table->get_Rows()->idx_get(0)->get_RowFormat()->get_HeightRule());
ASPOSE_ASSERT_EQ(100, table->get_Rows()->idx_get(1)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Exactly, table->get_Rows()->idx_get(1)->get_RowFormat()->get_HeightRule());
ASSERT_EQ(TextOrientation::Upward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(0)->get_CellFormat()->get_Orientation());
ASSERT_EQ(TextOrientation::Downward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(1)->get_CellFormat()->get_Orientation());
doc->Save(ArtifactsDir + u"DocumentBuilder.BuildTable.docx");

Shows how to format cells with a document builder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, cell 1.");
// Insert a second cell, and then configure cell text padding options.
// The builder will apply these settings at its current cell, and any new cells creates afterwards.
builder->InsertCell();
SharedPtr<CellFormat> cellFormat = builder->get_CellFormat();
cellFormat->set_Width(250);
cellFormat->set_LeftPadding(30);
cellFormat->set_RightPadding(30);
cellFormat->set_TopPadding(30);
cellFormat->set_BottomPadding(30);
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
builder->EndTable();
// The first cell was unaffected by the padding reconfiguration, and still holds the default values.
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_Width());
ASPOSE_ASSERT_EQ(5.4, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_LeftPadding());
ASPOSE_ASSERT_EQ(5.4, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_RightPadding());
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_TopPadding());
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_BottomPadding());
ASPOSE_ASSERT_EQ(250.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_Width());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_LeftPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_RightPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_TopPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_BottomPadding());
// The first cell will still grow in the output document to match the size of its neighboring cell.
doc->Save(ArtifactsDir + u"DocumentBuilder.SetCellFormatting.docx");

◆ get_Bold()

bool Aspose::Words::DocumentBuilder::get_Bold ( )

True if the font is formatted as bold.

Examples

Shows how to fill MERGEFIELDs with data with a document builder instead of a mail merge.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert some MERGEFIELDS, which accept data from columns of the same name in a data source during a mail merge,
// and then fill them manually.
builder->InsertField(u" MERGEFIELD Chairman ");
builder->InsertField(u" MERGEFIELD ChiefFinancialOfficer ");
builder->InsertField(u" MERGEFIELD ChiefTechnologyOfficer ");
builder->MoveToMergeField(u"Chairman");
builder->set_Bold(true);
builder->Writeln(u"John Doe");
builder->MoveToMergeField(u"ChiefFinancialOfficer");
builder->set_Italic(true);
builder->Writeln(u"Jane Doe");
builder->MoveToMergeField(u"ChiefTechnologyOfficer");
builder->set_Italic(true);
builder->Writeln(u"John Bloggs");
doc->Save(ArtifactsDir + u"DocumentBuilder.FillMergeFields.docx");

◆ get_CellFormat()

System::SharedPtr<Aspose::Words::Tables::CellFormat> Aspose::Words::DocumentBuilder::get_CellFormat ( )

Returns an object that represents current table cell formatting properties.

Examples

Shows how to build a table with custom borders.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->ClearFormatting();
builder->get_CellFormat()->set_Width(150);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_GreenYellow());
builder->get_CellFormat()->set_WrapText(false);
builder->get_CellFormat()->set_FitText(true);
builder->get_RowFormat()->ClearFormatting();
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_RowFormat()->set_Height(50);
builder->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::Engrave3D);
builder->get_RowFormat()->get_Borders()->set_Color(System::Drawing::Color::get_Orange());
builder->InsertCell();
builder->Write(u"Row 1, Col 1");
builder->InsertCell();
builder->Write(u"Row 1, Col 2");
builder->EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder->get_CellFormat()->get_Shading()->ClearFormatting();
builder->InsertCell();
builder->Write(u"Row 2, Col 1");
builder->InsertCell();
builder->Write(u"Row 2, Col 2");
builder->EndRow();
// Increase row height to fit the vertical text.
builder->InsertCell();
builder->get_RowFormat()->set_Height(150);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 3, Col 1");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 3, Col 2");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTable.docx");

Shows how to build a formatted 2x2 table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"Row 1, cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
// While building the table, the document builder will apply its current RowFormat/CellFormat property values
// to the current row/cell that its cursor is in and any new rows/cells as it creates them.
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(0)->get_CellFormat()->get_VerticalAlignment());
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(1)->get_CellFormat()->get_VerticalAlignment());
builder->InsertCell();
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 2, cell 1.");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 2, cell 2.");
builder->EndRow();
builder->EndTable();
// Previously added rows and cells are not retroactively affected by changes to the builder's formatting.
ASPOSE_ASSERT_EQ(0, table->get_Rows()->idx_get(0)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Auto, table->get_Rows()->idx_get(0)->get_RowFormat()->get_HeightRule());
ASPOSE_ASSERT_EQ(100, table->get_Rows()->idx_get(1)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Exactly, table->get_Rows()->idx_get(1)->get_RowFormat()->get_HeightRule());
ASSERT_EQ(TextOrientation::Upward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(0)->get_CellFormat()->get_Orientation());
ASSERT_EQ(TextOrientation::Downward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(1)->get_CellFormat()->get_Orientation());
doc->Save(ArtifactsDir + u"DocumentBuilder.BuildTable.docx");

Shows how to format cells with a document builder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, cell 1.");
// Insert a second cell, and then configure cell text padding options.
// The builder will apply these settings at its current cell, and any new cells creates afterwards.
builder->InsertCell();
SharedPtr<CellFormat> cellFormat = builder->get_CellFormat();
cellFormat->set_Width(250);
cellFormat->set_LeftPadding(30);
cellFormat->set_RightPadding(30);
cellFormat->set_TopPadding(30);
cellFormat->set_BottomPadding(30);
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
builder->EndTable();
// The first cell was unaffected by the padding reconfiguration, and still holds the default values.
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_Width());
ASPOSE_ASSERT_EQ(5.4, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_LeftPadding());
ASPOSE_ASSERT_EQ(5.4, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_RightPadding());
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_TopPadding());
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_BottomPadding());
ASPOSE_ASSERT_EQ(250.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_Width());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_LeftPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_RightPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_TopPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_BottomPadding());
// The first cell will still grow in the output document to match the size of its neighboring cell.
doc->Save(ArtifactsDir + u"DocumentBuilder.SetCellFormatting.docx");

◆ get_CurrentNode()

System::SharedPtr<Aspose::Words::Node> Aspose::Words::DocumentBuilder::get_CurrentNode ( )

Gets the node that is currently selected in this DocumentBuilder.

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.

See also
Aspose::Words::DocumentBuilder::get_CurrentParagraph
Examples

Shows how to move a document builder's cursor to different nodes in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a valid bookmark, an entity that consists of nodes enclosed by a bookmark start node,
// and a bookmark end node.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
SharedPtr<NodeCollection> firstParagraphNodes = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ChildNodes();
ASSERT_EQ(NodeType::BookmarkStart, firstParagraphNodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Run, firstParagraphNodes->idx_get(1)->get_NodeType());
ASSERT_EQ(u"Bookmark contents.", firstParagraphNodes->idx_get(1)->GetText().Trim());
ASSERT_EQ(NodeType::BookmarkEnd, firstParagraphNodes->idx_get(2)->get_NodeType());
// The document builder's cursor is always ahead of the node that we last added with it.
// If the builder's cursor is at the end of the document, its current node will be null.
// The previous node is the bookmark end node that we last added.
// Adding new nodes with the builder will append them to the last node.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// If we wish to edit a different part of the document with the builder,
// we will need to bring its cursor to the node we wish to edit.
builder->MoveToBookmark(u"MyBookmark");
// Moving it to a bookmark will move it to the first node within the bookmark start and end nodes, the enclosed run.
ASPOSE_ASSERT_EQ(firstParagraphNodes->idx_get(1), builder->get_CurrentNode());
// We can also move the cursor to an individual node like this.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph(), builder->get_CurrentParagraph());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// We can use specific methods to move to the start/end of a document.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

◆ get_CurrentParagraph()

System::SharedPtr<Aspose::Words::Paragraph> Aspose::Words::DocumentBuilder::get_CurrentParagraph ( )

Gets the paragraph that is currently selected in this DocumentBuilder.

Examples

Shows how to move a document builder's cursor to different nodes in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a valid bookmark, an entity that consists of nodes enclosed by a bookmark start node,
// and a bookmark end node.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
SharedPtr<NodeCollection> firstParagraphNodes = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ChildNodes();
ASSERT_EQ(NodeType::BookmarkStart, firstParagraphNodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Run, firstParagraphNodes->idx_get(1)->get_NodeType());
ASSERT_EQ(u"Bookmark contents.", firstParagraphNodes->idx_get(1)->GetText().Trim());
ASSERT_EQ(NodeType::BookmarkEnd, firstParagraphNodes->idx_get(2)->get_NodeType());
// The document builder's cursor is always ahead of the node that we last added with it.
// If the builder's cursor is at the end of the document, its current node will be null.
// The previous node is the bookmark end node that we last added.
// Adding new nodes with the builder will append them to the last node.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// If we wish to edit a different part of the document with the builder,
// we will need to bring its cursor to the node we wish to edit.
builder->MoveToBookmark(u"MyBookmark");
// Moving it to a bookmark will move it to the first node within the bookmark start and end nodes, the enclosed run.
ASPOSE_ASSERT_EQ(firstParagraphNodes->idx_get(1), builder->get_CurrentNode());
// We can also move the cursor to an individual node like this.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph(), builder->get_CurrentParagraph());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// We can use specific methods to move to the start/end of a document.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

◆ get_CurrentSection()

System::SharedPtr<Aspose::Words::Section> Aspose::Words::DocumentBuilder::get_CurrentSection ( )

Gets the section that is currently selected in this DocumentBuilder.

Examples

Shows how to insert a floating image, and specify its position and size.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Shape> shape = builder->InsertImage(ImageDir + u"Logo.jpg");
shape->set_WrapType(WrapType::None);
// Configure the shape's "RelativeHorizontalPosition" property to treat the value of the "Left" property
// as the shape's horizontal distance, in points, from the left side of the page.
shape->set_RelativeHorizontalPosition(RelativeHorizontalPosition::Page);
// Set the shape's horizontal distance from the left side of the page to 100.
shape->set_Left(100);
// Use the "RelativeVerticalPosition" property in a similar way to position the shape 80pt below the top of the page.
shape->set_RelativeVerticalPosition(RelativeVerticalPosition::Page);
shape->set_Top(80);
// Set the shape's height, which will automatically scale the width to preserve dimensions.
shape->set_Height(125);
ASPOSE_ASSERT_EQ(125.0, shape->get_Width());
// The "Bottom" and "Right" properties contain the bottom and right edges of the image.
ASPOSE_ASSERT_EQ(shape->get_Top() + shape->get_Height(), shape->get_Bottom());
ASPOSE_ASSERT_EQ(shape->get_Left() + shape->get_Width(), shape->get_Right());
doc->Save(ArtifactsDir + u"Image.CreateFloatingPositionSize.docx");

◆ get_CurrentStory()

System::SharedPtr<Aspose::Words::Story> Aspose::Words::DocumentBuilder::get_CurrentStory ( )

Gets the story that is currently selected in this DocumentBuilder.

Examples

Shows how to work with a document builder's current story.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// A Story is a type of node that has child Paragraph nodes, such as a Body.
ASPOSE_ASSERT_EQ(builder->get_CurrentStory(), doc->get_FirstSection()->get_Body());
ASPOSE_ASSERT_EQ(builder->get_CurrentStory(), builder->get_CurrentParagraph()->get_ParentNode());
ASSERT_EQ(StoryType::MainText, builder->get_CurrentStory()->get_StoryType());
builder->get_CurrentStory()->AppendParagraph(u"Text added to current Story.");
// A Story can also contain tables.
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, cell 1");
builder->InsertCell();
builder->Write(u"Row 1, cell 2");
builder->EndTable();
ASSERT_TRUE(builder->get_CurrentStory()->get_Tables()->Contains(table));

◆ get_Document()

System::SharedPtr<Aspose::Words::Document> Aspose::Words::DocumentBuilder::get_Document ( ) const

Gets or sets the Document object that this object is attached to.

Examples

Shows how to apply and revert page setup settings to sections in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Modify the page setup properties for the builder's current section and add text.
builder->get_PageSetup()->set_Orientation(Orientation::Landscape);
builder->get_PageSetup()->set_VerticalAlignment(PageVerticalAlignment::Center);
builder->Writeln(u"This is the first section, which landscape oriented with vertically centered text.");
// If we start a new section using a document builder,
// it will inherit the builder's current page setup properties.
builder->InsertBreak(BreakType::SectionBreakNewPage);
ASSERT_EQ(Orientation::Landscape, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_Orientation());
ASSERT_EQ(PageVerticalAlignment::Center, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_VerticalAlignment());
// We can revert its page setup properties to their default values using the "ClearFormatting" method.
builder->get_PageSetup()->ClearFormatting();
ASSERT_EQ(Orientation::Portrait, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_Orientation());
ASSERT_EQ(PageVerticalAlignment::Top, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_VerticalAlignment());
builder->Writeln(u"This is the second section, which is in default Letter paper size, portrait orientation and top alignment.");
doc->Save(ArtifactsDir + u"PageSetup.ClearFormatting.docx");

◆ get_Font()

System::SharedPtr<Aspose::Words::Font> Aspose::Words::DocumentBuilder::get_Font ( )

Returns an object that represents current font formatting properties.

Use Font to access and modify font formatting properties.

Specify font formatting before inserting text.

Examples

Shows how to insert a string surrounded by a border into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->get_Border()->set_Color(System::Drawing::Color::get_Green());
builder->get_Font()->get_Border()->set_LineWidth(2.5);
builder->get_Font()->get_Border()->set_LineStyle(LineStyle::DashDotStroker);
builder->Write(u"Text surrounded by green border.");
doc->Save(ArtifactsDir + u"Border.FontBorder.docx");

Shows how to create a formatted table using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
table->set_LeftIndent(20);
// Set some formatting options for text and table appearance.
builder->get_RowFormat()->set_Height(40);
builder->get_RowFormat()->set_HeightRule(HeightRule::AtLeast);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::FromArgb(198, 217, 241));
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_Font()->set_Size(16);
builder->get_Font()->set_Name(u"Arial");
builder->get_Font()->set_Bold(true);
// Configuring the formatting options in a document builder will apply them
// to the current cell/row its cursor is in,
// as well as any new cells and rows created using that builder.
builder->Write(u"Header Row,\n Cell 1");
builder->InsertCell();
builder->Write(u"Header Row,\n Cell 2");
builder->InsertCell();
builder->Write(u"Header Row,\n Cell 3");
builder->EndRow();
// Reconfigure the builder's formatting objects for new rows and cells that we are about to make.
// The builder will not apply these to the first row already created so that it will stand out as a header row.
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_White());
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_RowFormat()->set_Height(30);
builder->get_RowFormat()->set_HeightRule(HeightRule::Auto);
builder->InsertCell();
builder->get_Font()->set_Size(12);
builder->get_Font()->set_Bold(false);
builder->Write(u"Row 1, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, Cell 2.");
builder->InsertCell();
builder->Write(u"Row 1, Cell 3.");
builder->EndRow();
builder->InsertCell();
builder->Write(u"Row 2, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 2, Cell 2.");
builder->InsertCell();
builder->Write(u"Row 2, Cell 3.");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.CreateFormattedTable.docx");

◆ get_IsAtEndOfParagraph()

bool Aspose::Words::DocumentBuilder::get_IsAtEndOfParagraph ( )

Returns true if the cursor is at the end of the current paragraph.

Examples

Shows how to move a document builder's cursor to different nodes in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a valid bookmark, an entity that consists of nodes enclosed by a bookmark start node,
// and a bookmark end node.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
SharedPtr<NodeCollection> firstParagraphNodes = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ChildNodes();
ASSERT_EQ(NodeType::BookmarkStart, firstParagraphNodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Run, firstParagraphNodes->idx_get(1)->get_NodeType());
ASSERT_EQ(u"Bookmark contents.", firstParagraphNodes->idx_get(1)->GetText().Trim());
ASSERT_EQ(NodeType::BookmarkEnd, firstParagraphNodes->idx_get(2)->get_NodeType());
// The document builder's cursor is always ahead of the node that we last added with it.
// If the builder's cursor is at the end of the document, its current node will be null.
// The previous node is the bookmark end node that we last added.
// Adding new nodes with the builder will append them to the last node.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// If we wish to edit a different part of the document with the builder,
// we will need to bring its cursor to the node we wish to edit.
builder->MoveToBookmark(u"MyBookmark");
// Moving it to a bookmark will move it to the first node within the bookmark start and end nodes, the enclosed run.
ASPOSE_ASSERT_EQ(firstParagraphNodes->idx_get(1), builder->get_CurrentNode());
// We can also move the cursor to an individual node like this.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph(), builder->get_CurrentParagraph());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// We can use specific methods to move to the start/end of a document.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

◆ get_IsAtStartOfParagraph()

bool Aspose::Words::DocumentBuilder::get_IsAtStartOfParagraph ( )

Returns true if the cursor is at the beginning of the current paragraph (no text before the cursor).

Examples

Shows how to move a document builder's cursor to different nodes in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a valid bookmark, an entity that consists of nodes enclosed by a bookmark start node,
// and a bookmark end node.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
SharedPtr<NodeCollection> firstParagraphNodes = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ChildNodes();
ASSERT_EQ(NodeType::BookmarkStart, firstParagraphNodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Run, firstParagraphNodes->idx_get(1)->get_NodeType());
ASSERT_EQ(u"Bookmark contents.", firstParagraphNodes->idx_get(1)->GetText().Trim());
ASSERT_EQ(NodeType::BookmarkEnd, firstParagraphNodes->idx_get(2)->get_NodeType());
// The document builder's cursor is always ahead of the node that we last added with it.
// If the builder's cursor is at the end of the document, its current node will be null.
// The previous node is the bookmark end node that we last added.
// Adding new nodes with the builder will append them to the last node.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// If we wish to edit a different part of the document with the builder,
// we will need to bring its cursor to the node we wish to edit.
builder->MoveToBookmark(u"MyBookmark");
// Moving it to a bookmark will move it to the first node within the bookmark start and end nodes, the enclosed run.
ASPOSE_ASSERT_EQ(firstParagraphNodes->idx_get(1), builder->get_CurrentNode());
// We can also move the cursor to an individual node like this.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph(), builder->get_CurrentParagraph());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// We can use specific methods to move to the start/end of a document.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

◆ get_Italic()

bool Aspose::Words::DocumentBuilder::get_Italic ( )

True if the font is formatted as italic.

Examples

Shows how to fill MERGEFIELDs with data with a document builder instead of a mail merge.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert some MERGEFIELDS, which accept data from columns of the same name in a data source during a mail merge,
// and then fill them manually.
builder->InsertField(u" MERGEFIELD Chairman ");
builder->InsertField(u" MERGEFIELD ChiefFinancialOfficer ");
builder->InsertField(u" MERGEFIELD ChiefTechnologyOfficer ");
builder->MoveToMergeField(u"Chairman");
builder->set_Bold(true);
builder->Writeln(u"John Doe");
builder->MoveToMergeField(u"ChiefFinancialOfficer");
builder->set_Italic(true);
builder->Writeln(u"Jane Doe");
builder->MoveToMergeField(u"ChiefTechnologyOfficer");
builder->set_Italic(true);
builder->Writeln(u"John Bloggs");
doc->Save(ArtifactsDir + u"DocumentBuilder.FillMergeFields.docx");

◆ get_ListFormat()

System::SharedPtr<Aspose::Words::Lists::ListFormat> Aspose::Words::DocumentBuilder::get_ListFormat ( )

Returns an object that represents current list formatting properties.

Examples

Shows how to create bulleted and numbered lists.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Aspose.Words main advantages are:");
// A list allows us to organize and decorate sets of paragraphs with prefix symbols and indents.
// We can create nested lists by increasing the indent level.
// We can begin and end a list by using a document builder's "ListFormat" property.
// Each paragraph that we add between a list's start and the end will become an item in the list.
// Below are two types of lists that we can create with a document builder.
// 1 - A bulleted list:
// This list will apply an indent and a bullet symbol ("•") before each paragraph.
builder->get_ListFormat()->ApplyBulletDefault();
builder->Writeln(u"Great performance");
builder->Writeln(u"High reliability");
builder->Writeln(u"Quality code and working");
builder->Writeln(u"Wide variety of features");
builder->Writeln(u"Easy to understand API");
// End the bulleted list.
builder->get_ListFormat()->RemoveNumbers();
builder->InsertBreak(BreakType::ParagraphBreak);
builder->Writeln(u"Aspose.Words allows:");
// 2 - A numbered list:
// Numbered lists create a logical order for their paragraphs by numbering each item.
builder->get_ListFormat()->ApplyNumberDefault();
// This paragraph is the first item. The first item of a numbered list will have a "1." as its list item symbol.
builder->Writeln(u"Opening documents from different formats:");
ASSERT_EQ(0, builder->get_ListFormat()->get_ListLevelNumber());
// Call the "ListIndent" method to increase the current list level,
// which will start a new self-contained list, with a deeper indent, at the current item of the first list level.
builder->get_ListFormat()->ListIndent();
ASSERT_EQ(1, builder->get_ListFormat()->get_ListLevelNumber());
// These are the first three list items of the second list level, which will maintain a count
// independent of the count of the first list level. According to the current list format,
// they will have symbols of "a.", "b.", and "c.".
builder->Writeln(u"DOC");
builder->Writeln(u"PDF");
builder->Writeln(u"HTML");
// Call the "ListOutdent" method to return to the previous list level.
builder->get_ListFormat()->ListOutdent();
ASSERT_EQ(0, builder->get_ListFormat()->get_ListLevelNumber());
// These two paragraphs will continue the count of the first list level.
// These items will have symbols of "2.", and "3."
builder->Writeln(u"Processing documents");
builder->Writeln(u"Saving documents in different formats:");
// If we increase the list level to a level that we have added items to previously,
// the nested list will be separate from the previous, and its numbering will start from the beginning.
// These list items will have symbols of "a.", "b.", "c.", "d.", and "e".
builder->get_ListFormat()->ListIndent();
builder->Writeln(u"DOC");
builder->Writeln(u"PDF");
builder->Writeln(u"HTML");
builder->Writeln(u"MHTML");
builder->Writeln(u"Plain text");
// Outdent the list level again.
builder->get_ListFormat()->ListOutdent();
builder->Writeln(u"Doing many other things!");
// End the numbered list.
builder->get_ListFormat()->RemoveNumbers();
doc->Save(ArtifactsDir + u"Lists.ApplyDefaultBulletsAndNumbers.docx");

◆ get_PageSetup()

System::SharedPtr<Aspose::Words::PageSetup> Aspose::Words::DocumentBuilder::get_PageSetup ( )

Returns an object that represents current page setup and section properties.

Examples

Shows how to apply and revert page setup settings to sections in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Modify the page setup properties for the builder's current section and add text.
builder->get_PageSetup()->set_Orientation(Orientation::Landscape);
builder->get_PageSetup()->set_VerticalAlignment(PageVerticalAlignment::Center);
builder->Writeln(u"This is the first section, which landscape oriented with vertically centered text.");
// If we start a new section using a document builder,
// it will inherit the builder's current page setup properties.
builder->InsertBreak(BreakType::SectionBreakNewPage);
ASSERT_EQ(Orientation::Landscape, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_Orientation());
ASSERT_EQ(PageVerticalAlignment::Center, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_VerticalAlignment());
// We can revert its page setup properties to their default values using the "ClearFormatting" method.
builder->get_PageSetup()->ClearFormatting();
ASSERT_EQ(Orientation::Portrait, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_Orientation());
ASSERT_EQ(PageVerticalAlignment::Top, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_VerticalAlignment());
builder->Writeln(u"This is the second section, which is in default Letter paper size, portrait orientation and top alignment.");
doc->Save(ArtifactsDir + u"PageSetup.ClearFormatting.docx");

◆ get_ParagraphFormat()

System::SharedPtr<Aspose::Words::ParagraphFormat> Aspose::Words::DocumentBuilder::get_ParagraphFormat ( )

Returns an object that represents current paragraph formatting properties.

Examples

Shows how to create a formatted table using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
table->set_LeftIndent(20);
// Set some formatting options for text and table appearance.
builder->get_RowFormat()->set_Height(40);
builder->get_RowFormat()->set_HeightRule(HeightRule::AtLeast);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::FromArgb(198, 217, 241));
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_Font()->set_Size(16);
builder->get_Font()->set_Name(u"Arial");
builder->get_Font()->set_Bold(true);
// Configuring the formatting options in a document builder will apply them
// to the current cell/row its cursor is in,
// as well as any new cells and rows created using that builder.
builder->Write(u"Header Row,\n Cell 1");
builder->InsertCell();
builder->Write(u"Header Row,\n Cell 2");
builder->InsertCell();
builder->Write(u"Header Row,\n Cell 3");
builder->EndRow();
// Reconfigure the builder's formatting objects for new rows and cells that we are about to make.
// The builder will not apply these to the first row already created so that it will stand out as a header row.
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_White());
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_RowFormat()->set_Height(30);
builder->get_RowFormat()->set_HeightRule(HeightRule::Auto);
builder->InsertCell();
builder->get_Font()->set_Size(12);
builder->get_Font()->set_Bold(false);
builder->Write(u"Row 1, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, Cell 2.");
builder->InsertCell();
builder->Write(u"Row 1, Cell 3.");
builder->EndRow();
builder->InsertCell();
builder->Write(u"Row 2, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 2, Cell 2.");
builder->InsertCell();
builder->Write(u"Row 2, Cell 3.");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.CreateFormattedTable.docx");

◆ get_RowFormat()

System::SharedPtr<Aspose::Words::Tables::RowFormat> Aspose::Words::DocumentBuilder::get_RowFormat ( )

Returns an object that represents current table row formatting properties.

Examples

Shows how to build a table with custom borders.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->ClearFormatting();
builder->get_CellFormat()->set_Width(150);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_GreenYellow());
builder->get_CellFormat()->set_WrapText(false);
builder->get_CellFormat()->set_FitText(true);
builder->get_RowFormat()->ClearFormatting();
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_RowFormat()->set_Height(50);
builder->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::Engrave3D);
builder->get_RowFormat()->get_Borders()->set_Color(System::Drawing::Color::get_Orange());
builder->InsertCell();
builder->Write(u"Row 1, Col 1");
builder->InsertCell();
builder->Write(u"Row 1, Col 2");
builder->EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder->get_CellFormat()->get_Shading()->ClearFormatting();
builder->InsertCell();
builder->Write(u"Row 2, Col 1");
builder->InsertCell();
builder->Write(u"Row 2, Col 2");
builder->EndRow();
// Increase row height to fit the vertical text.
builder->InsertCell();
builder->get_RowFormat()->set_Height(150);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 3, Col 1");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 3, Col 2");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTable.docx");

Shows how to build a formatted 2x2 table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"Row 1, cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
// While building the table, the document builder will apply its current RowFormat/CellFormat property values
// to the current row/cell that its cursor is in and any new rows/cells as it creates them.
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(0)->get_CellFormat()->get_VerticalAlignment());
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(1)->get_CellFormat()->get_VerticalAlignment());
builder->InsertCell();
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 2, cell 1.");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 2, cell 2.");
builder->EndRow();
builder->EndTable();
// Previously added rows and cells are not retroactively affected by changes to the builder's formatting.
ASPOSE_ASSERT_EQ(0, table->get_Rows()->idx_get(0)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Auto, table->get_Rows()->idx_get(0)->get_RowFormat()->get_HeightRule());
ASPOSE_ASSERT_EQ(100, table->get_Rows()->idx_get(1)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Exactly, table->get_Rows()->idx_get(1)->get_RowFormat()->get_HeightRule());
ASSERT_EQ(TextOrientation::Upward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(0)->get_CellFormat()->get_Orientation());
ASSERT_EQ(TextOrientation::Downward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(1)->get_CellFormat()->get_Orientation());
doc->Save(ArtifactsDir + u"DocumentBuilder.BuildTable.docx");

Shows how to format rows with a document builder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, cell 1.");
// Start a second row, and then configure its height. The builder will apply these settings to
// its current row, as well as any new rows it creates afterwards.
builder->EndRow();
SharedPtr<RowFormat> rowFormat = builder->get_RowFormat();
rowFormat->set_Height(100);
rowFormat->set_HeightRule(HeightRule::Exactly);
builder->InsertCell();
builder->Write(u"Row 2, cell 1.");
builder->EndTable();
// The first row was unaffected by the padding reconfiguration and still holds the default values.
ASPOSE_ASSERT_EQ(0.0, table->get_Rows()->idx_get(0)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Auto, table->get_Rows()->idx_get(0)->get_RowFormat()->get_HeightRule());
ASPOSE_ASSERT_EQ(100.0, table->get_Rows()->idx_get(1)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Exactly, table->get_Rows()->idx_get(1)->get_RowFormat()->get_HeightRule());
doc->Save(ArtifactsDir + u"DocumentBuilder.SetRowFormatting.docx");

◆ get_Underline()

Aspose::Words::Underline Aspose::Words::DocumentBuilder::get_Underline ( )

Gets/sets underline type for the current font.

Examples

Shows how to format text inserted by a document builder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->set_Underline(Underline::Dash);
builder->get_Font()->set_Color(System::Drawing::Color::get_Blue());
builder->get_Font()->set_Size(32);
// The builder applies formatting to its current paragraph and any new text added by it afterward.
builder->Writeln(u"Large, blue, and underlined text.");
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertUnderline.docx");

◆ GetType()

virtual const System::TypeInfo& Aspose::Words::DocumentBuilder::GetType ( ) const
overridevirtual

◆ InsertBreak()

void Aspose::Words::DocumentBuilder::InsertBreak ( Aspose::Words::BreakType  breakType)

Inserts a break of the specified type into the document.

Parameters
breakTypeSpecifies the type of the break to insert.
Examples

Shows how to create headers and footers in a document using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Specify that we want different headers and footers for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers, then add three pages to the document to display each header type.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header for the first page");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header for even pages");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header for all other pages");
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page3");
doc->Save(ArtifactsDir + u"DocumentBuilder.HeadersAndFooters.docx");

Shows how to insert a Table of contents (TOC) into a document using heading styles as entries.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a table of contents for the first page of the document.
// Configure the table to pick up paragraphs with headings of levels 1 to 3.
// Also, set its entries to be hyperlinks that will take us
// to the location of the heading when left-clicked in Microsoft Word.
builder->InsertTableOfContents(u"\\o \"1-3\" \\h \\z \\u");
builder->InsertBreak(BreakType::PageBreak);
// Populate the table of contents by adding paragraphs with heading styles.
// Each such heading with a level between 1 and 3 will create an entry in the table.
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 1.1");
builder->Writeln(u"Heading 1.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 2");
builder->Writeln(u"Heading 3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading3);
builder->Writeln(u"Heading 3.1.1");
builder->Writeln(u"Heading 3.1.2");
builder->Writeln(u"Heading 3.1.3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading4);
builder->Writeln(u"Heading 3.1.3.1");
builder->Writeln(u"Heading 3.1.3.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.2");
builder->Writeln(u"Heading 3.3");
// A table of contents is a field of a type that needs to be updated to show an up-to-date result.
doc->UpdateFields();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertToc.docx");

Shows how to apply and revert page setup settings to sections in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Modify the page setup properties for the builder's current section and add text.
builder->get_PageSetup()->set_Orientation(Orientation::Landscape);
builder->get_PageSetup()->set_VerticalAlignment(PageVerticalAlignment::Center);
builder->Writeln(u"This is the first section, which landscape oriented with vertically centered text.");
// If we start a new section using a document builder,
// it will inherit the builder's current page setup properties.
builder->InsertBreak(BreakType::SectionBreakNewPage);
ASSERT_EQ(Orientation::Landscape, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_Orientation());
ASSERT_EQ(PageVerticalAlignment::Center, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_VerticalAlignment());
// We can revert its page setup properties to their default values using the "ClearFormatting" method.
builder->get_PageSetup()->ClearFormatting();
ASSERT_EQ(Orientation::Portrait, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_Orientation());
ASSERT_EQ(PageVerticalAlignment::Top, doc->get_Sections()->idx_get(1)->get_PageSetup()->get_VerticalAlignment());
builder->Writeln(u"This is the second section, which is in default Letter paper size, portrait orientation and top alignment.");
doc->Save(ArtifactsDir + u"PageSetup.ClearFormatting.docx");

◆ InsertCell()

System::SharedPtr<Aspose::Words::Tables::Cell> Aspose::Words::DocumentBuilder::InsertCell ( )

Inserts a table cell into the document.

To start a table, just call InsertCell. After this, any content you add using other methods of the DocumentBuilder class will be added to the current cell.

To start a new cell in the same row, call InsertCell again.

To end a table row call EndRow.

Use the CellFormat property to specify cell formatting.

Returns
The cell node that was just inserted.
Examples

Shows how to build a table with custom borders.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->ClearFormatting();
builder->get_CellFormat()->set_Width(150);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_GreenYellow());
builder->get_CellFormat()->set_WrapText(false);
builder->get_CellFormat()->set_FitText(true);
builder->get_RowFormat()->ClearFormatting();
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_RowFormat()->set_Height(50);
builder->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::Engrave3D);
builder->get_RowFormat()->get_Borders()->set_Color(System::Drawing::Color::get_Orange());
builder->InsertCell();
builder->Write(u"Row 1, Col 1");
builder->InsertCell();
builder->Write(u"Row 1, Col 2");
builder->EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder->get_CellFormat()->get_Shading()->ClearFormatting();
builder->InsertCell();
builder->Write(u"Row 2, Col 1");
builder->InsertCell();
builder->Write(u"Row 2, Col 2");
builder->EndRow();
// Increase row height to fit the vertical text.
builder->InsertCell();
builder->get_RowFormat()->set_Height(150);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 3, Col 1");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 3, Col 2");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTable.docx");

Shows how to use a document builder to create a table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Start the table, then populate the first row with two cells.
builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, Cell 2.");
// Call the builder's "EndRow" method to start a new row.
builder->EndRow();
builder->InsertCell();
builder->Write(u"Row 2, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 2, Cell 2.");
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.CreateTable.docx");

◆ InsertChart() [1/2]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertChart ( Aspose::Words::Drawing::Charts::ChartType  chartType,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts an chart object into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
chartTypeThe chart type to insert into the document.
horzPosSpecifies where the distance to the image is measured from.
leftDistance in points from the origin to the left side of the image.
vertPosSpecifies where the distance to the image measured from.
topDistance in points from the origin to the top side of the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
wrapTypeSpecifies how to wrap text around the image.
Returns
The image node that was just inserted.
Examples

Shows how to specify position and wrapping while inserting a chart.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertChart(ChartType::Pie, RelativeHorizontalPosition::Margin, 100, RelativeVerticalPosition::Margin, 100, 200, 100, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertedChartRelativePosition.docx");

◆ InsertChart() [2/2]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertChart ( Aspose::Words::Drawing::Charts::ChartType  chartType,
double  width,
double  height 
)

Inserts an chart object into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
chartTypeThe chart type to insert into the document.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
Returns
The image node that was just inserted.
Examples

Shows how to insert a pie chart into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Chart> chart = builder->InsertChart(ChartType::Pie, ConvertUtil::PixelToPoint(300), ConvertUtil::PixelToPoint(300))->get_Chart();
chart->get_Series()->Clear();
chart->get_Series()->Add(u"My fruit", MakeArray<String>({u"Apples", u"Bananas", u"Cherries"}), MakeArray<double>({1.3, 2.2, 1.5}));
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertPieChart.docx");

◆ InsertCheckBox() [1/2]

System::SharedPtr<Aspose::Words::Fields::FormField> Aspose::Words::DocumentBuilder::InsertCheckBox ( const System::String name,
bool  checkedValue,
int32_t  size 
)

Inserts a checkbox form field at the current position.

If you specify a name for the form field, then a bookmark is automatically created with the same name.

Parameters
nameThe name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.
checkedValueChecked status of the checkbox form field.
sizeSpecifies the size of the checkbox in points. Specify 0 for MS Word to calculate the size of the checkbox automatically.
Returns
The form field node that was just inserted.
Examples

Shows how to insert checkboxes into the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert checkboxes of varying sizes and default checked statuses.
builder->Write(u"Unchecked check box of a default size: ");
builder->InsertCheckBox(String::Empty, false, false, 0);
builder->InsertParagraph();
builder->Write(u"Large checked check box: ");
builder->InsertCheckBox(u"CheckBox_Default", true, true, 50);
builder->InsertParagraph();
// Form fields have a name length limit of 20 characters.
builder->Write(u"Very large checked check box: ");
builder->InsertCheckBox(u"CheckBox_OnlyCheckedValue", true, 100);
ASSERT_EQ(u"CheckBox_OnlyChecked", doc->get_Range()->get_FormFields()->idx_get(2)->get_Name());
// We can interact with these check boxes in Microsoft Word by double clicking them.
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertCheckBox.docx");

◆ InsertCheckBox() [2/2]

System::SharedPtr<Aspose::Words::Fields::FormField> Aspose::Words::DocumentBuilder::InsertCheckBox ( const System::String name,
bool  defaultValue,
bool  checkedValue,
int32_t  size 
)

Inserts a checkbox form field at the current position.

If you specify a name for the form field, then a bookmark is automatically created with the same name.

Parameters
nameThe name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.
defaultValueDefault value of the checkbox form field.
checkedValueCurrent checked status of the checkbox form field.
sizeSpecifies the size of the checkbox in points. Specify 0 for MS Word to calculate the size of the checkbox automatically.
Returns
The form field node that was just inserted.
Examples

Shows how to insert checkboxes into the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert checkboxes of varying sizes and default checked statuses.
builder->Write(u"Unchecked check box of a default size: ");
builder->InsertCheckBox(String::Empty, false, false, 0);
builder->InsertParagraph();
builder->Write(u"Large checked check box: ");
builder->InsertCheckBox(u"CheckBox_Default", true, true, 50);
builder->InsertParagraph();
// Form fields have a name length limit of 20 characters.
builder->Write(u"Very large checked check box: ");
builder->InsertCheckBox(u"CheckBox_OnlyCheckedValue", true, 100);
ASSERT_EQ(u"CheckBox_OnlyChecked", doc->get_Range()->get_FormFields()->idx_get(2)->get_Name());
// We can interact with these check boxes in Microsoft Word by double clicking them.
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertCheckBox.docx");

◆ InsertComboBox()

System::SharedPtr<Aspose::Words::Fields::FormField> Aspose::Words::DocumentBuilder::InsertComboBox ( const System::String name,
const System::ArrayPtr< System::String > &  items,
int32_t  selectedIndex 
)

Inserts a combobox form field at the current position.

If you specify a name for the form field, then a bookmark is automatically created with the same name.

Parameters
nameThe name of the form field. Can be an empty string. The value longer than 20 characters will be truncated.
itemsThe items of the ComboBox. Maximum is 25 items.
selectedIndexThe index of the selected item in the ComboBox.
Returns
The form field node that was just inserted.
Examples

Shows how to create form fields.

auto builder = MakeObject<DocumentBuilder>();
// Form fields are objects in the document that the user can interact with by being prompted to enter values.
// We can create them using a document builder, and below are two ways of doing so.
// 1 - Basic text input:
builder->InsertTextInput(u"My text input", TextFormFieldType::Regular, u"", u"Enter your name here", 30);
// 2 - Combo box with prompt text, and a range of possible values:
ArrayPtr<String> items = MakeArray<String>({u"-- Select your favorite footwear --", u"Sneakers", u"Oxfords", u"Flip-flops", u"Other"});
builder->InsertParagraph();
builder->InsertComboBox(u"My combo box", items, 0);
builder->get_Document()->Save(ArtifactsDir + u"DocumentBuilder.CreateForm.docx");

Shows how to insert a combo box form field into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a form that prompts the user to pick one of the items from the menu.
builder->Write(u"Pick a fruit: ");
ArrayPtr<String> items = MakeArray<String>({u"Apple", u"Banana", u"Cherry"});
builder->InsertComboBox(u"DropDown", items, 0);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertComboBox.docx");

◆ InsertDocument() [1/2]

System::SharedPtr<Aspose::Words::Node> Aspose::Words::DocumentBuilder::InsertDocument ( const System::SharedPtr< Aspose::Words::Document > &  srcDoc,
Aspose::Words::ImportFormatMode  importFormatMode 
)

Inserts a document at the cursor position.

Parameters
srcDocSource document for inserting.
importFormatModeSpecifies how to merge style formatting that clashes.
Returns
First node of the inserted content.
Examples

Shows how to insert a document into another document.

auto doc = MakeObject<Document>(MyDir + u"Document.docx");
auto builder = MakeObject<DocumentBuilder>(doc);
builder->MoveToDocumentEnd();
builder->InsertBreak(BreakType::PageBreak);
auto docToInsert = MakeObject<Document>(MyDir + u"Formatted elements.docx");
builder->InsertDocument(docToInsert, ImportFormatMode::KeepSourceFormatting);
builder->get_Document()->Save(ArtifactsDir + u"DocumentBuilder.InsertDocument.docx");

◆ InsertDocument() [2/2]

System::SharedPtr<Aspose::Words::Node> Aspose::Words::DocumentBuilder::InsertDocument ( const System::SharedPtr< Aspose::Words::Document > &  srcDoc,
Aspose::Words::ImportFormatMode  importFormatMode,
const System::SharedPtr< Aspose::Words::ImportFormatOptions > &  importFormatOptions 
)

Inserts a document at the cursor position.

Parameters
srcDocSource document for inserting.
importFormatModeSpecifies how to merge style formatting that clashes.
importFormatOptionsAllows to specify options that affect formatting of a result document.
Returns
First node of the inserted content.
Examples

Shows how to resolve duplicate styles while inserting documents.

auto dstDoc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(dstDoc);
SharedPtr<Style> myStyle = builder->get_Document()->get_Styles()->Add(StyleType::Paragraph, u"MyStyle");
myStyle->get_Font()->set_Size(14);
myStyle->get_Font()->set_Name(u"Courier New");
myStyle->get_Font()->set_Color(System::Drawing::Color::get_Blue());
builder->get_ParagraphFormat()->set_StyleName(myStyle->get_Name());
builder->Writeln(u"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 insert the clone into the original document, the two styles with the same name will cause a clash.
SharedPtr<Document> srcDoc = dstDoc->Clone();
srcDoc->get_Styles()->idx_get(u"MyStyle")->get_Font()->set_Color(System::Drawing::Color::get_Red());
// When we enable SmartStyleBehavior and use the KeepSourceFormatting import format mode,
// Aspose.Words will resolve style clashes by converting source document styles.
// with the same names as destination styles into direct paragraph attributes.
auto options = MakeObject<ImportFormatOptions>();
options->set_SmartStyleBehavior(true);
builder->InsertDocument(srcDoc, ImportFormatMode::KeepSourceFormatting, options);
dstDoc->Save(ArtifactsDir + u"DocumentBuilder.SmartStyleBehavior.docx");

◆ InsertField() [1/3]

System::SharedPtr<Aspose::Words::Fields::Field> Aspose::Words::DocumentBuilder::InsertField ( Aspose::Words::Fields::FieldType  fieldType,
bool  updateField 
)

Inserts a Word field into a document and optionally updates the field result.

This method inserts a field into a document. Aspose.Words can update fields of most types, but not all. For more details see the InsertField() overload.

Parameters
fieldTypeThe type of the field to append.
updateFieldSpecifies whether to update the field immediately.
Returns
A Field object that represents the inserted field.
See also
Aspose::Words::Fields::Field
Examples

Shows how to insert a field into a document using FieldType.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert two fields while passing a flag which determines whether to update them as the builder inserts them.
// In some cases, updating fields could be computationally expensive, and it may be a good idea to defer the update.
doc->get_BuiltInDocumentProperties()->set_Author(u"John Doe");
builder->Write(u"This document was written by ");
builder->InsertField(FieldType::FieldAuthor, updateInsertedFieldsImmediately);
builder->InsertParagraph();
builder->Write(u"\nThis is page ");
builder->InsertField(FieldType::FieldPage, updateInsertedFieldsImmediately);
ASSERT_EQ(u" AUTHOR ", doc->get_Range()->get_Fields()->idx_get(0)->GetFieldCode());
ASSERT_EQ(u" PAGE ", doc->get_Range()->get_Fields()->idx_get(1)->GetFieldCode());
if (updateInsertedFieldsImmediately)
{
ASSERT_EQ(u"John Doe", doc->get_Range()->get_Fields()->idx_get(0)->get_Result());
ASSERT_EQ(u"1", doc->get_Range()->get_Fields()->idx_get(1)->get_Result());
}
else
{
ASSERT_EQ(String::Empty, doc->get_Range()->get_Fields()->idx_get(0)->get_Result());
ASSERT_EQ(String::Empty, doc->get_Range()->get_Fields()->idx_get(1)->get_Result());
// We will need to update these fields using the update methods manually.
doc->get_Range()->get_Fields()->idx_get(0)->Update();
ASSERT_EQ(u"John Doe", doc->get_Range()->get_Fields()->idx_get(0)->get_Result());
doc->UpdateFields();
ASSERT_EQ(u"1", doc->get_Range()->get_Fields()->idx_get(1)->get_Result());
}

◆ InsertField() [2/3]

System::SharedPtr<Aspose::Words::Fields::Field> Aspose::Words::DocumentBuilder::InsertField ( const System::String fieldCode)

Inserts a Word field into a document and updates the field result.

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 InsertField() overload.

Parameters
fieldCodeThe field code to insert (without curly braces).
Returns
A Field object that represents the inserted field.
See also
Aspose::Words::Fields::Field
Examples

Shows how to insert fields, and move the document builder's cursor to them.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD MyMergeField1 \\* MERGEFORMAT");
builder->InsertField(u"MERGEFIELD MyMergeField2 \\* MERGEFORMAT");
// Move the cursor to the first MERGEFIELD.
builder->MoveToMergeField(u"MyMergeField1", true, false);
// Note that the cursor is placed immediately after the first MERGEFIELD, and before the second.
ASPOSE_ASSERT_EQ(doc->get_Range()->get_Fields()->idx_get(1)->get_Start(), builder->get_CurrentNode());
ASPOSE_ASSERT_EQ(doc->get_Range()->get_Fields()->idx_get(0)->get_End(), builder->get_CurrentNode()->get_PreviousSibling());
// If we wish to edit the field's field code or contents using the builder,
// its cursor would need to be inside a field.
// To place it inside a field, we would need to call the document builder's MoveTo method
// and pass the field's start or separator node as an argument.
builder->Write(u" Text between our merge fields. ");
doc->Save(ArtifactsDir + u"DocumentBuilder.MergeFields.docx");

Shows how to insert a field into a document using a field code.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Field> field = builder->InsertField(u"DATE \\@ \"dddd, MMMM dd, yyyy\"");
ASSERT_EQ(FieldType::FieldDate, field->get_Type());
ASSERT_EQ(u"DATE \\@ \"dddd, MMMM dd, yyyy\"", field->GetFieldCode());
// This overload of the InsertField method automatically updates inserted fields.
ASSERT_LE(System::Math::Abs((System::DateTime::Parse(field->get_Result()) - System::DateTime::get_Today()).get_Hours()), 24);

◆ InsertField() [3/3]

System::SharedPtr<Aspose::Words::Fields::Field> Aspose::Words::DocumentBuilder::InsertField ( const System::String fieldCode,
const System::String fieldValue 
)

Inserts a Word field into a document without updating the field result.

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 Update on the field object returned to you or UpdateFields to update fields in the whole document.

Parameters
fieldCodeThe field code to insert (without curly braces).
fieldValueThe field value to insert. Pass null for fields that do not have a value.
Returns
A Field object that represents the inserted field.
See also
Aspose::Words::Fields::Field
Examples

Shows how to set up page numbering in a section.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Section 1, page 1.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Section 1, page 2.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Section 1, page 3.");
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->Writeln(u"Section 2, page 1.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Section 2, page 2.");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Section 2, page 3.");
// Move the document builder to the first section's primary header,
// which every page in that section will display.
builder->MoveToSection(0);
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
// Insert a PAGE field, which will display the number of the current page.
builder->Write(u"Page ");
builder->InsertField(u"PAGE", u"");
// Configure the section to have the page count that PAGE fields display start from 5.
// Also, configure all PAGE fields to display their page numbers using uppercase Roman numerals.
SharedPtr<PageSetup> pageSetup = doc->get_Sections()->idx_get(0)->get_PageSetup();
pageSetup->set_RestartPageNumbering(true);
pageSetup->set_PageStartingNumber(5);
pageSetup->set_PageNumberStyle(NumberStyle::UppercaseRoman);
// Create another primary header for the second section, with another PAGE field.
builder->MoveToSection(1);
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->Write(u" - ");
builder->InsertField(u"PAGE", u"");
builder->Write(u" - ");
// Configure the section to have the page count that PAGE fields display start from 10.
// Also, configure all PAGE fields to display their page numbers using Arabic numbers.
pageSetup = doc->get_Sections()->idx_get(1)->get_PageSetup();
pageSetup->set_PageStartingNumber(10);
pageSetup->set_RestartPageNumbering(true);
pageSetup->set_PageNumberStyle(NumberStyle::Arabic);
doc->Save(ArtifactsDir + u"PageSetup.PageNumbering.docx");

◆ InsertFootnote() [1/2]

System::SharedPtr<Aspose::Words::Notes::Footnote> Aspose::Words::DocumentBuilder::InsertFootnote ( Aspose::Words::Notes::FootnoteType  footnoteType,
const System::String footnoteText 
)

Inserts a footnote or endnote into the document.

Parameters
footnoteTypeSpecifies whether to insert a footnote or an endnote.
footnoteTextSpecifies the text of the footnote.
Returns
Returns a footnote object that was just created.
Examples

Shows how to reference text with a footnote and an endnote.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert some text and mark it with a footnote with the IsAuto property 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(u"This text will be referenced by a footnote.");
builder->InsertFootnote(FootnoteType::Footnote, u"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 set "IsAuto" to false.
builder->Write(u"This text will be referenced by an endnote.");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote comment regarding referenced text.", u"CustomMark");
// Footnotes always appear at the bottom 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 that this page break will push the endnote down to the next page.
builder->InsertBreak(BreakType::PageBreak);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertFootnote.docx");

◆ InsertFootnote() [2/2]

System::SharedPtr<Aspose::Words::Notes::Footnote> Aspose::Words::DocumentBuilder::InsertFootnote ( Aspose::Words::Notes::FootnoteType  footnoteType,
const System::String footnoteText,
const System::String referenceMark 
)

Inserts a footnote or endnote into the document.

Parameters
footnoteTypeSpecifies whether to insert a footnote or an endnote.
footnoteTextSpecifies the text of the footnote.
referenceMarkSpecifies the custom reference mark of the footnote.
Returns
Returns a footnote object that was just created.
Examples

Shows how to reference text with a footnote and an endnote.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert some text and mark it with a footnote with the IsAuto property 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(u"This text will be referenced by a footnote.");
builder->InsertFootnote(FootnoteType::Footnote, u"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 set "IsAuto" to false.
builder->Write(u"This text will be referenced by an endnote.");
builder->InsertFootnote(FootnoteType::Endnote, u"Endnote comment regarding referenced text.", u"CustomMark");
// Footnotes always appear at the bottom 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 that this page break will push the endnote down to the next page.
builder->InsertBreak(BreakType::PageBreak);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertFootnote.docx");

◆ InsertHorizontalRule()

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertHorizontalRule ( )

Inserts a horizontal rule shape into the document.

Returns
The shape that is a horizontal rule.
Examples

Shows how to insert a horizontal rule shape, and customize its formatting.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Shape> shape = builder->InsertHorizontalRule();
SharedPtr<HorizontalRuleFormat> horizontalRuleFormat = shape->get_HorizontalRuleFormat();
horizontalRuleFormat->set_Alignment(HorizontalRuleAlignment::Center);
horizontalRuleFormat->set_WidthPercent(70);
horizontalRuleFormat->set_Height(3);
horizontalRuleFormat->set_Color(System::Drawing::Color::get_Blue());
horizontalRuleFormat->set_NoShade(true);
ASSERT_TRUE(shape->get_IsHorizontalRule());
ASSERT_TRUE(shape->get_HorizontalRuleFormat()->get_NoShade());

◆ InsertHtml() [1/3]

void Aspose::Words::DocumentBuilder::InsertHtml ( const System::String html)

Inserts an HTML string into the document.

Parameters
htmlAn HTML string to insert into the document.
Examples

Shows how to use a document builder to insert html content into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
const String html = String(u"<p align='right'>Paragraph right</p>") + u"<b>Implicit paragraph left</b>" + u"<div align='center'>Div center</div>" +
u"<h1 align='left'>Heading 1 left.</h1>";
builder->InsertHtml(html);
// Inserting HTML code parses the formatting of each element into equivalent document text formatting.
SharedPtr<ParagraphCollection> paragraphs = doc->get_FirstSection()->get_Body()->get_Paragraphs();
ASSERT_EQ(u"Paragraph right", paragraphs->idx_get(0)->GetText().Trim());
ASSERT_EQ(ParagraphAlignment::Right, paragraphs->idx_get(0)->get_ParagraphFormat()->get_Alignment());
ASSERT_EQ(u"Implicit paragraph left", paragraphs->idx_get(1)->GetText().Trim());
ASSERT_EQ(ParagraphAlignment::Left, paragraphs->idx_get(1)->get_ParagraphFormat()->get_Alignment());
ASSERT_TRUE(paragraphs->idx_get(1)->get_Runs()->idx_get(0)->get_Font()->get_Bold());
ASSERT_EQ(u"Div center", paragraphs->idx_get(2)->GetText().Trim());
ASSERT_EQ(ParagraphAlignment::Center, paragraphs->idx_get(2)->get_ParagraphFormat()->get_Alignment());
ASSERT_EQ(u"Heading 1 left.", paragraphs->idx_get(3)->GetText().Trim());
ASSERT_EQ(u"Heading 1", paragraphs->idx_get(3)->get_ParagraphFormat()->get_Style()->get_Name());
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertHtml.docx");

Shows how to execute a mail merge with a custom callback that handles merge data in the form of HTML documents.

void MergeHtml()
{
auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD html_Title \\b Content");
builder->InsertField(u"MERGEFIELD html_Body \\b Content");
ArrayPtr<SharedPtr<System::Object>> mergeData = MakeArray<SharedPtr<System::Object>>(
{System::ObjectExt::Box<String>(String(u"<html>") + u"<h1>" + u"<span style=\"color: #0000ff; font-family: Arial;\">Hello World!</span>" +
u"</h1>" + u"</html>"),
System::ObjectExt::Box<String>(
String(u"<html>") + u"<blockquote>" +
u"<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>" +
u"</blockquote>" + u"</html>")});
doc->get_MailMerge()->set_FieldMergingCallback(MakeObject<ExMailMergeEvent::HandleMergeFieldInsertHtml>());
doc->get_MailMerge()->Execute(MakeArray<String>({u"html_Title", u"html_Body"}), mergeData);
doc->Save(ArtifactsDir + u"MailMergeEvent.MergeHtml.docx");
}
class HandleMergeFieldInsertHtml : public IFieldMergingCallback
{
public:
void FieldMerging(SharedPtr<FieldMergingArgs> args) override
{
if (args->get_DocumentFieldName().StartsWith(u"html_") && args->get_Field()->GetFieldCode().Contains(u"\\b"))
{
// Add parsed HTML data to the document's body.
auto builder = MakeObject<DocumentBuilder>(args->get_Document());
builder->MoveToMergeField(args->get_DocumentFieldName());
builder->InsertHtml(System::ObjectExt::Unbox<String>(args->get_FieldValue()));
// Since we have already inserted the merged content manually,
// we will not need to respond to this event by returning content via the "Text" property.
args->set_Text(String::Empty);
}
}
void ImageFieldMerging(SharedPtr<ImageFieldMergingArgs> args) override
{
// Do nothing.
}
};

◆ InsertHtml() [2/3]

void Aspose::Words::DocumentBuilder::InsertHtml ( const System::String html,
Aspose::Words::HtmlInsertOptions  options 
)

Inserts an HTML string into the document. Allows to specify additional options.

Parameters
htmlAn HTML string to insert into the document.
optionsOptions that are used when HTML string is inserted.

◆ InsertHtml() [3/3]

void Aspose::Words::DocumentBuilder::InsertHtml ( const System::String html,
bool  useBuilderFormatting 
)

Inserts an HTML string into the document.

You can use this method to insert an HTML fragment or whole HTML document.

When useBuilderFormatting is false, DocumentBuilder formating is ignored and formatting of inserted text is based on default HTML formatting. As a result, the text looks as it is rendered in browsers.

When useBuilderFormatting is true, formatting of inserted text is based on DocumentBuilder formatting, and the text looks as if it were inserted with Write().

Parameters
htmlAn HTML string to insert into the document.
useBuilderFormattingA value indicating whether formatting specified in DocumentBuilder is used as base formatting for text imported from HTML.
Examples

Shows how to apply a document builder's formatting while inserting HTML content.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Set a text alignment for the builder, insert an HTML paragraph with a specified alignment, and one without.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Distributed);
builder->InsertHtml(String(u"<p align='right'>Paragraph 1.</p>") + u"<p>Paragraph 2.</p>", useBuilderFormatting);
SharedPtr<ParagraphCollection> paragraphs = doc->get_FirstSection()->get_Body()->get_Paragraphs();
// The first paragraph has an alignment specified. When InsertHtml parses the HTML code,
// the paragraph alignment value found in the HTML code always supersedes the document builder's value.
ASSERT_EQ(u"Paragraph 1.", paragraphs->idx_get(0)->GetText().Trim());
ASSERT_EQ(ParagraphAlignment::Right, paragraphs->idx_get(0)->get_ParagraphFormat()->get_Alignment());
// The second paragraph has no alignment specified. It can have its alignment value filled in
// by the builder's value depending on the flag we passed to the InsertHtml method.
ASSERT_EQ(u"Paragraph 2.", paragraphs->idx_get(1)->GetText().Trim());
ASSERT_EQ(useBuilderFormatting ? ParagraphAlignment::Distributed : ParagraphAlignment::Left,
paragraphs->idx_get(1)->get_ParagraphFormat()->get_Alignment());
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertHtmlWithFormatting.docx");

◆ InsertHyperlink()

System::SharedPtr<Aspose::Words::Fields::Field> Aspose::Words::DocumentBuilder::InsertHyperlink ( const System::String displayText,
const System::String urlOrBookmark,
bool  isBookmark 
)

Inserts a hyperlink into the document.

Note that you need to specify font formatting for the hyperlink display text explicitly using the Font property.

This methods internally calls InsertField() to insert an MS Word HYPERLINK field into the document.

Parameters
displayTextText of the link to be displayed in the document.
urlOrBookmarkLink 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.
isBookmarkTrue if the previous parameter is a name of a bookmark inside the document; false is the previous parameter is a URL.
Returns
A Field object that represents the inserted field.
Examples

Shows how to insert a hyperlink field.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"For more information, please visit the ");
// Insert a hyperlink and emphasize it with custom formatting.
// The hyperlink will be a clickable piece of text which will take us to the location specified in the URL.
builder->get_Font()->set_Color(System::Drawing::Color::get_Blue());
builder->get_Font()->set_Underline(Underline::Single);
builder->InsertHyperlink(u"Google website", u"https://www.google.com", false);
builder->get_Font()->ClearFormatting();
builder->Writeln(u".");
// Ctrl + left clicking the link in the text in Microsoft Word will take us to the URL via a new web browser window.
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertHyperlink.docx");

Shows how to use a document builder's formatting stack.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Set up font formatting, then write the text that goes before the hyperlink.
builder->get_Font()->set_Name(u"Arial");
builder->get_Font()->set_Size(24);
builder->Write(u"To visit Google, hold Ctrl and click ");
// Preserve our current formatting configuration on the stack.
builder->PushFont();
// Alter the builder's current formatting by applying a new style.
builder->get_Font()->set_StyleIdentifier(StyleIdentifier::Hyperlink);
builder->InsertHyperlink(u"here", u"http://www.google.com", false);
ASSERT_EQ(System::Drawing::Color::get_Blue().ToArgb(), builder->get_Font()->get_Color().ToArgb());
ASSERT_EQ(Underline::Single, builder->get_Font()->get_Underline());
// Restore the font formatting that we saved earlier and remove the element from the stack.
builder->PopFont();
ASSERT_EQ(System::Drawing::Color::Empty.ToArgb(), builder->get_Font()->get_Color().ToArgb());
ASSERT_EQ(Underline::None, builder->get_Font()->get_Underline());
builder->Write(u". We hope you enjoyed the example.");
doc->Save(ArtifactsDir + u"DocumentBuilder.PushPopFont.docx");

Shows how to insert a hyperlink which references a local bookmark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartBookmark(u"Bookmark1");
builder->Write(u"Bookmarked text. ");
builder->EndBookmark(u"Bookmark1");
builder->Writeln(u"Text outside of the bookmark.");
// Insert a HYPERLINK field that links to the bookmark. We can pass field switches
// to the "InsertHyperlink" method as part of the argument containing the referenced bookmark's name.
builder->get_Font()->set_Color(System::Drawing::Color::get_Blue());
builder->get_Font()->set_Underline(Underline::Single);
builder->InsertHyperlink(u"Link to Bookmark1", u"Bookmark1\" \\o \"Hyperlink Tip", true);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertHyperlinkToLocalBookmark.docx");

◆ InsertImage() [1/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::ArrayPtr< uint8_t > &  imageBytes)

Inserts an image from a byte array into the document. The image is inserted inline and at 100% scale.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
imageBytesThe byte array that contains the image.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from a byte array into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromFile(ImageDir + u"Logo.jpg");
{
auto ms = MakeObject<System::IO::MemoryStream>();
ArrayPtr<uint8_t> imageByteArray = ms->ToArray();
// Below are three ways of inserting an image from a byte array.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(imageByteArray);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(imageByteArray, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(imageByteArray, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0,
WrapType::Square);
}
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromByteArray.docx");

◆ InsertImage() [2/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::ArrayPtr< uint8_t > &  imageBytes,
double  width,
double  height 
)

Inserts an inline image from a byte array into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
imageBytesThe byte array that contains the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from a byte array into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromFile(ImageDir + u"Logo.jpg");
{
auto ms = MakeObject<System::IO::MemoryStream>();
ArrayPtr<uint8_t> imageByteArray = ms->ToArray();
// Below are three ways of inserting an image from a byte array.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(imageByteArray);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(imageByteArray, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(imageByteArray, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0,
WrapType::Square);
}
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromByteArray.docx");

◆ InsertImage() [3/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::SharedPtr< System::Drawing::Image > &  image)

Inserts an image from a Image object into the document. The image is inserted inline and at 100% scale.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
imageThe image to insert into the document.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from an object into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromFile(ImageDir + u"Logo.jpg");
// Below are three ways of inserting an image from an Image object instance.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(image);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(image, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(image, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromImageObject.docx");

◆ InsertImage() [4/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::SharedPtr< System::Drawing::Image > &  image,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts an image from a Image object at the specified position and size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
imageThe image to insert into the document.
horzPosSpecifies where the distance to the image is measured from.
leftDistance in points from the origin to the left side of the image.
vertPosSpecifies where the distance to the image measured from.
topDistance in points from the origin to the top side of the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
wrapTypeSpecifies how to wrap text around the image.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from an object into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromFile(ImageDir + u"Logo.jpg");
// Below are three ways of inserting an image from an Image object instance.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(image);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(image, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(image, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromImageObject.docx");

◆ InsertImage() [5/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::SharedPtr< System::Drawing::Image > &  image,
double  width,
double  height 
)

Inserts an inline image from a Image object into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
imageThe image to insert into the document.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from an object into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromFile(ImageDir + u"Logo.jpg");
// Below are three ways of inserting an image from an Image object instance.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(image);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(image, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(image, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromImageObject.docx");

◆ InsertImage() [6/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::SharedPtr< System::IO::Stream > &  stream)

Inserts an image from a stream into the document. The image is inserted inline and at 100% scale.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
streamThe stream that contains the image.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from a stream into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
{
SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(ImageDir + u"Logo.jpg");
// Below are three ways of inserting an image from a stream.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(stream);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(stream, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(stream, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0, WrapType::Square);
}
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromStream.docx");

Shows how to insert a shape with an image from a stream into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
{
SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(ImageDir + u"Logo.jpg");
builder->Write(u"Image from stream: ");
builder->InsertImage(stream);
}
doc->Save(ArtifactsDir + u"Image.FromStream.docx");

◆ InsertImage() [7/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::SharedPtr< System::IO::Stream > &  stream,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts an image from a stream at the specified position and size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
streamThe stream that contains the image.
horzPosSpecifies where the distance to the image is measured from.
leftDistance in points from the origin to the left side of the image.
vertPosSpecifies where the distance to the image measured from.
topDistance in points from the origin to the top side of the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
wrapTypeSpecifies how to wrap text around the image.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from a stream into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
{
SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(ImageDir + u"Logo.jpg");
// Below are three ways of inserting an image from a stream.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(stream);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(stream, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(stream, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0, WrapType::Square);
}
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromStream.docx");

◆ InsertImage() [8/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::SharedPtr< System::IO::Stream > &  stream,
double  width,
double  height 
)

Inserts an inline image from a stream into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
streamThe stream that contains the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from a stream into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
{
SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(ImageDir + u"Logo.jpg");
// Below are three ways of inserting an image from a stream.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(stream);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(stream, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(stream, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0, WrapType::Square);
}
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromStream.docx");

◆ InsertImage() [9/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::String fileName)

Inserts an image from a file or URL into the document. The image is inserted inline and at 100% scale.

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 Shape object returned by this method.

Parameters
fileNameThe file with the image. Can be any valid local or remote URI.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from the local file system into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Below are three ways of inserting an image from a local system filename.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(ImageDir + u"Logo.jpg");
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(ImageDir + u"Transparent background logo.png", ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(ImageDir + u"Windows MetaFile.wmf", RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0,
100.0, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromFilename.docx");

Shows how to determine which image will be inserted.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertImage(ImageDir + u"Scalable Vector Graphics.svg");
// Aspose.Words insert SVG image to the document as PNG with svgBlip extension
// that contains the original vector SVG image representation.
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertSvgImage.SvgWithSvgBlip.docx");
// Aspose.Words insert SVG image to the document as PNG, just like Microsoft Word does for old format.
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertSvgImage.Svg.doc");
doc->get_CompatibilityOptions()->OptimizeFor(MsWordVersion::Word2003);
// Aspose.Words insert SVG image to the document as EMF metafile to keep the image in vector representation.
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertSvgImage.Emf.docx");

Shows how to insert a shape with an image into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Below are two locations where the document builder's "InsertShape" method
// can source the image that the shape will display.
// 1 - Pass a local file system filename of an image file:
builder->Write(u"Image from local file: ");
builder->InsertImage(ImageDir + u"Logo.jpg");
builder->Writeln();
// 2 - Pass a URL which points to an image.
builder->Write(u"Image from a URL: ");
builder->InsertImage(AsposeLogoUrl);
builder->Writeln();
doc->Save(ArtifactsDir + u"Image.FromUrl.docx");

Shows how to insert a floating image to the center of a page.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a floating image that will appear behind the overlapping text and align it to the page's center.
SharedPtr<Shape> shape = builder->InsertImage(ImageDir + u"Logo.jpg");
shape->set_WrapType(WrapType::None);
shape->set_BehindText(true);
shape->set_RelativeHorizontalPosition(RelativeHorizontalPosition::Page);
shape->set_RelativeVerticalPosition(RelativeVerticalPosition::Page);
shape->set_HorizontalAlignment(HorizontalAlignment::Center);
shape->set_VerticalAlignment(VerticalAlignment::Center);
doc->Save(ArtifactsDir + u"Image.CreateFloatingPageCenter.docx");

◆ InsertImage() [10/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::String fileName,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts an image from a file or URL at the specified position and size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
fileNameThe file that contains the image.
horzPosSpecifies where the distance to the image is measured from.
leftDistance in points from the origin to the left side of the image.
vertPosSpecifies where the distance to the image measured from.
topDistance in points from the origin to the top side of the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
wrapTypeSpecifies how to wrap text around the image.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// There are two ways of using a document builder to source an image and then insert it as a floating shape.
// 1 - From a file in the local file system:
builder->InsertImage(ImageDir + u"Transparent background logo.png", RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 0.0,
200.0, 200.0, WrapType::Square);
// 2 - From a URL:
builder->InsertImage(AsposeLogoUrl, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 250.0, 200.0, 200.0, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertFloatingImage.docx");

Shows how to insert an image from the local file system into a document while preserving its dimensions.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// The InsertImage method creates a floating shape with the passed image in its image data.
// We can specify the dimensions of the shape can be passing them to this method.
SharedPtr<Shape> imageShape = builder->InsertImage(ImageDir + u"Logo.jpg", RelativeHorizontalPosition::Margin, 0.0, RelativeVerticalPosition::Margin,
0.0, -1.0, -1.0, WrapType::Square);
// Passing negative values as the intended dimensions will automatically define
// the shape's dimensions based on the dimensions of its image.
ASPOSE_ASSERT_EQ(300.0, imageShape->get_Width());
ASPOSE_ASSERT_EQ(300.0, imageShape->get_Height());
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertImageOriginalSize.docx");

Shows how to insert an image from the local file system into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Below are three ways of inserting an image from a local system filename.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(ImageDir + u"Logo.jpg");
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(ImageDir + u"Transparent background logo.png", ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(ImageDir + u"Windows MetaFile.wmf", RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0,
100.0, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromFilename.docx");

◆ InsertImage() [11/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( const System::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.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
fileNameThe file that contains the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from the local file system into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Below are three ways of inserting an image from a local system filename.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(ImageDir + u"Logo.jpg");
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(ImageDir + u"Transparent background logo.png", ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(ImageDir + u"Windows MetaFile.wmf", RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0,
100.0, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromFilename.docx");

◆ InsertImage() [12/15]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( std::basic_istream< CharType, Traits > &  stream)
inline

◆ InsertImage() [13/15]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( std::basic_istream< CharType, Traits > &  stream,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)
inline

◆ InsertImage() [14/15]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( std::basic_istream< CharType, Traits > &  stream,
double  width,
double  height 
)
inline

◆ InsertImage() [15/15]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertImage ( System::ArrayPtr< uint8_t >  imageBytes,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts an image from a byte array at the specified position and size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
imageBytesThe byte array that contains the image.
horzPosSpecifies where the distance to the image is measured from.
leftDistance in points from the origin to the left side of the image.
vertPosSpecifies where the distance to the image measured from.
topDistance in points from the origin to the top side of the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
wrapTypeSpecifies how to wrap text around the image.
Returns
The image node that was just inserted.
Examples

Shows how to insert an image from a byte array into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromFile(ImageDir + u"Logo.jpg");
{
auto ms = MakeObject<System::IO::MemoryStream>();
ArrayPtr<uint8_t> imageByteArray = ms->ToArray();
// Below are three ways of inserting an image from a byte array.
// 1 - Inline shape with a default size based on the image's original dimensions:
builder->InsertImage(imageByteArray);
builder->InsertBreak(BreakType::PageBreak);
// 2 - Inline shape with custom dimensions:
builder->InsertImage(imageByteArray, ConvertUtil::PixelToPoint(250), ConvertUtil::PixelToPoint(144));
builder->InsertBreak(BreakType::PageBreak);
// 3 - Floating shape with custom dimensions:
builder->InsertImage(imageByteArray, RelativeHorizontalPosition::Margin, 100.0, RelativeVerticalPosition::Margin, 100.0, 200.0, 100.0,
WrapType::Square);
}
doc->Save(ArtifactsDir + u"DocumentBuilderImages.InsertImageFromByteArray.docx");

◆ InsertNode()

void Aspose::Words::DocumentBuilder::InsertNode ( const System::SharedPtr< Aspose::Words::Node > &  node)

Inserts a text level node inside the current paragraph before the cursor.

Examples

Shows how to insert a linked image into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
String imageFileName = ImageDir + u"Windows MetaFile.wmf";
// Below are two ways of applying an image to a shape so that it can display it.
// 1 - Set the shape to contain the image.
auto shape = MakeObject<Shape>(builder->get_Document(), ShapeType::Image);
shape->set_WrapType(WrapType::Inline);
shape->get_ImageData()->SetImage(imageFileName);
builder->InsertNode(shape);
doc->Save(ArtifactsDir + u"Image.CreateLinkedImage.Embedded.docx");
// Every image that we store in shape will increase the size of our document.
ASSERT_TRUE(70000 < MakeObject<System::IO::FileInfo>(ArtifactsDir + u"Image.CreateLinkedImage.Embedded.docx")->get_Length());
doc->get_FirstSection()->get_Body()->get_FirstParagraph()->RemoveAllChildren();
// 2 - Set the shape to link to an image file in the local file system.
shape = MakeObject<Shape>(builder->get_Document(), ShapeType::Image);
shape->set_WrapType(WrapType::Inline);
shape->get_ImageData()->set_SourceFullName(imageFileName);
builder->InsertNode(shape);
doc->Save(ArtifactsDir + u"Image.CreateLinkedImage.Linked.docx");
// Linking to images will save space and result in a smaller document.
// However, the document can only display the image correctly while
// the image file is present at the location that the shape's "SourceFullName" property points to.
ASSERT_TRUE(10000 > MakeObject<System::IO::FileInfo>(ArtifactsDir + u"Image.CreateLinkedImage.Linked.docx")->get_Length());

◆ InsertOleObject() [1/6]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObject ( const System::SharedPtr< System::IO::Stream > &  stream,
const System::String progId,
bool  asIcon,
const System::SharedPtr< System::IO::Stream > &  presentation 
)

Inserts an embedded OLE object from a stream into the document.

Parameters
streamStream containing application data.
progIdProgrammatic Identifier of OLE object.
asIconSpecifies either Iconic or Normal mode of OLE object being inserted.
presentationImage presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.
Returns
Shape node containing Ole object and inserted at the current Builder position.

◆ InsertOleObject() [2/6]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObject ( const System::String fileName,
bool  isLinked,
bool  asIcon,
const System::SharedPtr< System::IO::Stream > &  presentation 
)

Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using file extension.

Parameters
fileNameFull path to the file.
isLinkedIf true then linked OLE object is inserted otherwise embedded OLE object is inserted.
asIconSpecifies either Iconic or Normal mode of OLE object being inserted.
presentationImage presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.
Returns
Shape node containing Ole object and inserted at the current Builder position.

◆ InsertOleObject() [3/6]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObject ( const System::String fileName,
const System::String progId,
bool  isLinked,
bool  asIcon,
const System::SharedPtr< System::IO::Stream > &  presentation 
)

Inserts an embedded or linked OLE object from a file into the document. Detects OLE object type using given progID parameter.

Parameters
fileNameFull path to the file.
progIdProgId of OLE object.
isLinkedIf true then linked OLE object is inserted otherwise embedded OLE object is inserted.
asIconSpecifies either Iconic or Normal mode of OLE object being inserted.
presentationImage presentation of OLE object. If value is null Aspose.Words will use one of the predefined images.
Returns
Shape node containing Ole object and inserted at the current Builder position.

◆ InsertOleObject() [4/6]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObject ( std::basic_istream< CharType, Traits > &  stream,
System::String  progId,
bool  asIcon,
std::basic_istream< CharType, Traits > &  presentation 
)
inline

◆ InsertOleObject() [5/6]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObject ( System::String  fileName,
bool  isLinked,
bool  asIcon,
std::basic_istream< CharType, Traits > &  presentation 
)
inline

◆ InsertOleObject() [6/6]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObject ( System::String  fileName,
System::String  progId,
bool  isLinked,
bool  asIcon,
std::basic_istream< CharType, Traits > &  presentation 
)
inline

◆ InsertOleObjectAsIcon() [1/4]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObjectAsIcon ( const System::SharedPtr< System::IO::Stream > &  stream,
const System::String progId,
const System::String iconFile,
const System::String iconCaption 
)

Inserts an embedded OLE object as icon from a stream into the document. Allows to specify icon file and caption. Detects OLE object type using given progID parameter.

Parameters
streamStream containing application data.
progIdProgId of OLE object.
iconFileFull path to the ICO file. If the value is null, Aspose.Words will use a predefined image.
iconCaptionIcon caption. If the value is null, Aspose.Words will use the a predefined icon caption.
Returns
Shape node containing Ole object and inserted at the current Builder position.
Examples

Shows how to insert an embedded or linked OLE object as icon into the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// If 'iconFile' and 'iconCaption' are omitted, this overloaded method selects
// the icon according to 'progId' and uses the filename for the icon caption.
builder->InsertOleObjectAsIcon(MyDir + u"Presentation.pptx", u"Package", false, ImageDir + u"Logo icon.ico", u"My embedded file");
builder->InsertBreak(BreakType::LineBreak);
{
auto stream = MakeObject<System::IO::FileStream>(MyDir + u"Presentation.pptx", System::IO::FileMode::Open);
// If 'iconFile' and 'iconCaption' are omitted, this overloaded method selects
// the icon according to the file extension and uses the filename for the icon caption.
SharedPtr<Shape> shape = builder->InsertOleObjectAsIcon(stream, u"PowerPoint.Application", ImageDir + u"Logo icon.ico", u"My embedded file stream");
SharedPtr<OlePackage> setOlePackage = shape->get_OleFormat()->get_OlePackage();
setOlePackage->set_FileName(u"Presentation.pptx");
setOlePackage->set_DisplayName(u"Presentation.pptx");
}
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertOleObjectAsIcon.docx");

◆ InsertOleObjectAsIcon() [2/4]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObjectAsIcon ( const System::String fileName,
bool  isLinked,
const System::String iconFile,
const System::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.

Parameters
fileNameFull path to the file.
isLinkedIf true then linked OLE object is inserted otherwise embedded OLE object is inserted.
iconFileFull path to the ICO file. If the value is null, Aspose.Words will use a predefined image.
iconCaptionIcon caption. If the value is null, Aspose.Words will use the file name.
Returns
Shape node containing Ole object and inserted at the current Builder position.

◆ InsertOleObjectAsIcon() [3/4]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObjectAsIcon ( const System::String fileName,
const System::String progId,
bool  isLinked,
const System::String iconFile,
const System::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 given progID parameter.

Parameters
fileNameFull path to the file.
progIdProgId of OLE object.
isLinkedIf true then linked OLE object is inserted otherwise embedded OLE object is inserted.
iconFileFull path to the ICO file. If the value is null, Aspose.Words will use a predefined image.
iconCaptionIcon caption. If the value is null, Aspose.Words will use the file name.
Returns
Shape node containing Ole object and inserted at the current Builder position.
Examples

Shows how to insert an embedded or linked OLE object as icon into the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// If 'iconFile' and 'iconCaption' are omitted, this overloaded method selects
// the icon according to 'progId' and uses the filename for the icon caption.
builder->InsertOleObjectAsIcon(MyDir + u"Presentation.pptx", u"Package", false, ImageDir + u"Logo icon.ico", u"My embedded file");
builder->InsertBreak(BreakType::LineBreak);
{
auto stream = MakeObject<System::IO::FileStream>(MyDir + u"Presentation.pptx", System::IO::FileMode::Open);
// If 'iconFile' and 'iconCaption' are omitted, this overloaded method selects
// the icon according to the file extension and uses the filename for the icon caption.
SharedPtr<Shape> shape = builder->InsertOleObjectAsIcon(stream, u"PowerPoint.Application", ImageDir + u"Logo icon.ico", u"My embedded file stream");
SharedPtr<OlePackage> setOlePackage = shape->get_OleFormat()->get_OlePackage();
setOlePackage->set_FileName(u"Presentation.pptx");
setOlePackage->set_DisplayName(u"Presentation.pptx");
}
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertOleObjectAsIcon.docx");

◆ InsertOleObjectAsIcon() [4/4]

template<typename CharType , typename Traits >
System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOleObjectAsIcon ( std::basic_istream< CharType, Traits > &  stream,
System::String  progId,
System::String  iconFile,
System::String  iconCaption 
)
inline

◆ InsertOnlineVideo() [1/4]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOnlineVideo ( const System::String videoUrl,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts an online video object into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Insertion of online video from the following resources is supported:

If your online video is not displaying correctly, use InsertOnlineVideo(), which accepts custom embedded html code.

The code for embedding video can vary between providers, consult your corresponding provider of choice for details.

Parameters
videoUrlThe URL to the video.
horzPosSpecifies where the distance to the image is measured from.
leftDistance in points from the origin to the left side of the image.
vertPosSpecifies where the distance to the image measured from.
topDistance in points from the origin to the top side of the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
wrapTypeSpecifies how to wrap text around the image.
Returns
The image node that was just inserted.
Examples

Shows how to insert an online video into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
String videoUrl = u"https://vimeo.com/52477838";
// Insert a shape that plays a video from the web when clicked in Microsoft Word.
// This rectangular shape will contain an image based on the first frame of the linked video
// and a "play button" visual prompt. The video has an aspect ratio of 16:9.
// We will set the shape's size to that ratio, so the image does not appear stretched.
builder->InsertOnlineVideo(videoUrl, RelativeHorizontalPosition::LeftMargin, 0, RelativeVerticalPosition::TopMargin, 0, 320, 180, WrapType::Square);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertOnlineVideo.docx");

◆ InsertOnlineVideo() [2/4]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOnlineVideo ( const System::String videoUrl,
const System::String videoEmbedCode,
const System::ArrayPtr< uint8_t > &  thumbnailImageBytes,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts an online video object into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
videoUrlThe URL to the video.
videoEmbedCodeThe embed code for the video.
thumbnailImageBytesThe thumbnail image bytes.
horzPosSpecifies where the distance to the image is measured from.
leftDistance in points from the origin to the left side of the image.
vertPosSpecifies where the distance to the image measured from.
topDistance in points from the origin to the top side of the image.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
wrapTypeSpecifies how to wrap text around the image.
Returns
The image node that was just inserted.
Examples

Shows how to insert an online video into a document with a custom thumbnail.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
String videoUrl = u"https://vimeo.com/52477838";
String videoEmbedCode = String(u"<iframe src=\"https://player.vimeo.com/video/52477838\" width=\"640\" height=\"360\" frameborder=\"0\" ") +
u"title=\"Aspose\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";
ArrayPtr<uint8_t> thumbnailImageBytes = System::IO::File::ReadAllBytes(ImageDir + u"Logo.jpg");
{
auto stream = MakeObject<System::IO::MemoryStream>(thumbnailImageBytes);
{
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromStream(stream);
// Below are two ways of creating a shape with a custom thumbnail, which links to an online video
// that will play when we click on the shape in Microsoft Word.
// 1 - Insert an inline shape at the builder's node insertion cursor:
builder->InsertOnlineVideo(videoUrl, videoEmbedCode, thumbnailImageBytes, image->get_Width(), image->get_Height());
builder->InsertBreak(BreakType::PageBreak);
// 2 - Insert a floating shape:
double left = builder->get_PageSetup()->get_RightMargin() - image->get_Width();
double top = builder->get_PageSetup()->get_BottomMargin() - image->get_Height();
builder->InsertOnlineVideo(videoUrl, videoEmbedCode, thumbnailImageBytes, RelativeHorizontalPosition::RightMargin, left,
RelativeVerticalPosition::BottomMargin, top, image->get_Width(), image->get_Height(), WrapType::Square);
}
}
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertOnlineVideoCustomThumbnail.docx");

◆ InsertOnlineVideo() [3/4]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOnlineVideo ( const System::String videoUrl,
const System::String videoEmbedCode,
const System::ArrayPtr< uint8_t > &  thumbnailImageBytes,
double  width,
double  height 
)

Inserts an online video object into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
videoUrlThe URL to the video.
videoEmbedCodeThe embed code for the video.
thumbnailImageBytesThe thumbnail image bytes.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
Returns
The image node that was just inserted.
Examples

Shows how to insert an online video into a document with a custom thumbnail.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
String videoUrl = u"https://vimeo.com/52477838";
String videoEmbedCode = String(u"<iframe src=\"https://player.vimeo.com/video/52477838\" width=\"640\" height=\"360\" frameborder=\"0\" ") +
u"title=\"Aspose\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";
ArrayPtr<uint8_t> thumbnailImageBytes = System::IO::File::ReadAllBytes(ImageDir + u"Logo.jpg");
{
auto stream = MakeObject<System::IO::MemoryStream>(thumbnailImageBytes);
{
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromStream(stream);
// Below are two ways of creating a shape with a custom thumbnail, which links to an online video
// that will play when we click on the shape in Microsoft Word.
// 1 - Insert an inline shape at the builder's node insertion cursor:
builder->InsertOnlineVideo(videoUrl, videoEmbedCode, thumbnailImageBytes, image->get_Width(), image->get_Height());
builder->InsertBreak(BreakType::PageBreak);
// 2 - Insert a floating shape:
double left = builder->get_PageSetup()->get_RightMargin() - image->get_Width();
double top = builder->get_PageSetup()->get_BottomMargin() - image->get_Height();
builder->InsertOnlineVideo(videoUrl, videoEmbedCode, thumbnailImageBytes, RelativeHorizontalPosition::RightMargin, left,
RelativeVerticalPosition::BottomMargin, top, image->get_Width(), image->get_Height(), WrapType::Square);
}
}
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertOnlineVideoCustomThumbnail.docx");

◆ InsertOnlineVideo() [4/4]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertOnlineVideo ( const System::String videoUrl,
double  width,
double  height 
)

Inserts an online video object into the document and scales it to the specified size.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Insertion of online video from the following resources is supported:

If your online video is not displaying correctly, use InsertOnlineVideo(), which accepts custom embedded html code.

The code for embedding video can vary between providers, consult your corresponding provider of choice for details.

Parameters
videoUrlThe URL to the video.
widthThe width of the image in points. Can be a negative or zero value to request 100% scale.
heightThe height of the image in points. Can be a negative or zero value to request 100% scale.
Returns
The image node that was just inserted.
Examples

Shows how to insert an online video into a document using a URL.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertOnlineVideo(u"https://youtu.be/t_1LYZ102RA", 360, 270);
// We can watch the video from Microsoft Word by clicking on the shape.
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertVideoWithUrl.docx");

◆ InsertParagraph()

System::SharedPtr<Aspose::Words::Paragraph> Aspose::Words::DocumentBuilder::InsertParagraph ( )

Inserts a paragraph break into the document.

Current paragraph formatting specified by the ParagraphFormat property is used.

Breaks the current paragraph in two. After inserting the paragraph, the cursor is placed at the beginning of the new paragraph.

Returns
The paragraph node that was just inserted. It is the same node as CurrentParagraph.
Examples

Shows how to insert a paragraph into the document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Font> font = builder->get_Font();
font->set_Size(16);
font->set_Bold(true);
font->set_Name(u"Arial");
font->set_Underline(Underline::Dash);
SharedPtr<ParagraphFormat> paragraphFormat = builder->get_ParagraphFormat();
paragraphFormat->set_FirstLineIndent(8);
paragraphFormat->set_Alignment(ParagraphAlignment::Justify);
paragraphFormat->set_AddSpaceBetweenFarEastAndAlpha(true);
paragraphFormat->set_AddSpaceBetweenFarEastAndDigit(true);
paragraphFormat->set_KeepTogether(true);
// The "Writeln" method ends the paragraph after appending text
// and then starts a new line, adding a new paragraph.
builder->Writeln(u"Hello world!");
ASSERT_TRUE(builder->get_CurrentParagraph()->get_IsEndOfDocument());

◆ InsertShape() [1/2]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertShape ( Aspose::Words::Drawing::ShapeType  shapeType,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
double  width,
double  height,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts free-floating shape with specified position, size and text wrap type.

Parameters
shapeTypeThe shape type to insert into the document
horzPosSpecifies where the horizontal distance to the shape is measured from.
leftDistance in points from the origin to the left side of the shape.
vertPosSpecifies where the vertical distance to the shape is measured from.
topDistance in points from the origin to the top side of the shape.
widthThe width of the shape in points.
heightThe width of the shape in points.
wrapTypeSpecifies how to wrap text around the shape.
Returns
The shape node that was inserted.
Examples

Shows how to insert DML shapes into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Below are two wrapping types that shapes may have.
// 1 - Floating:
builder->InsertShape(ShapeType::TopCornersRounded, RelativeHorizontalPosition::Page, 100, RelativeVerticalPosition::Page, 100, 50, 50, WrapType::None);
// 2 - Inline:
builder->InsertShape(ShapeType::DiagonalCornersRounded, 50, 50);
// If you need to create "non-primitive" shapes, such as SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped,
// TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, or DiagonalCornersRounded,
// then save the document with "Strict" or "Transitional" compliance, which allows saving shape as DML.
auto saveOptions = MakeObject<OoxmlSaveOptions>(SaveFormat::Docx);
saveOptions->set_Compliance(OoxmlCompliance::Iso29500_2008_Transitional);
doc->Save(ArtifactsDir + u"Shape.ShapeInsertion.docx", saveOptions);

◆ InsertShape() [2/2]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertShape ( Aspose::Words::Drawing::ShapeType  shapeType,
double  width,
double  height 
)

Inserts inline shape with specified type and size.

Parameters
shapeTypeThe shape type to insert into the document.
widthThe width of the shape in points.
heightThe height of the shape in points.
Returns
The shape node that was inserted.
Examples

Shows how to insert DML shapes into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Below are two wrapping types that shapes may have.
// 1 - Floating:
builder->InsertShape(ShapeType::TopCornersRounded, RelativeHorizontalPosition::Page, 100, RelativeVerticalPosition::Page, 100, 50, 50, WrapType::None);
// 2 - Inline:
builder->InsertShape(ShapeType::DiagonalCornersRounded, 50, 50);
// If you need to create "non-primitive" shapes, such as SingleCornerSnipped, TopCornersSnipped, DiagonalCornersSnipped,
// TopCornersOneRoundedOneSnipped, SingleCornerRounded, TopCornersRounded, or DiagonalCornersRounded,
// then save the document with "Strict" or "Transitional" compliance, which allows saving shape as DML.
auto saveOptions = MakeObject<OoxmlSaveOptions>(SaveFormat::Docx);
saveOptions->set_Compliance(OoxmlCompliance::Iso29500_2008_Transitional);
doc->Save(ArtifactsDir + u"Shape.ShapeInsertion.docx", saveOptions);

◆ InsertSignatureLine() [1/2]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertSignatureLine ( const System::SharedPtr< Aspose::Words::SignatureLineOptions > &  signatureLineOptions)

Inserts a signature line at the current position.

Parameters
signatureLineOptionsThe object that stores parameters of creating signature line.
Returns
The signature line node that was just inserted.
Examples

Shows how to sign a document with a personal certificate and a signature line.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
auto signatureLineOptions = MakeObject<SignatureLineOptions>();
signatureLineOptions->set_Signer(u"vderyushev");
signatureLineOptions->set_SignerTitle(u"QA");
signatureLineOptions->set_Email(u"vderyushev@aspose.com");
signatureLineOptions->set_ShowDate(true);
signatureLineOptions->set_DefaultInstructions(false);
signatureLineOptions->set_Instructions(u"Please sign here.");
signatureLineOptions->set_AllowComments(true);
SharedPtr<SignatureLine> signatureLine = builder->InsertSignatureLine(signatureLineOptions)->get_SignatureLine();
signatureLine->set_ProviderId(System::Guid::Parse(u"CF5A7BB4-8F3C-4756-9DF6-BEF7F13259A2"));
ASSERT_FALSE(signatureLine->get_IsSigned());
ASSERT_FALSE(signatureLine->get_IsValid());
doc->Save(ArtifactsDir + u"DocumentBuilder.SignatureLineProviderId.docx");
auto signOptions = MakeObject<SignOptions>();
signOptions->set_SignatureLineId(signatureLine->get_Id());
signOptions->set_ProviderId(signatureLine->get_ProviderId());
signOptions->set_Comments(u"Document was signed by vderyushev");
signOptions->set_SignTime(System::DateTime::get_Now());
SharedPtr<CertificateHolder> certHolder = CertificateHolder::Create(MyDir + u"morzal.pfx", u"aw");
DigitalSignatureUtil::Sign(ArtifactsDir + u"DocumentBuilder.SignatureLineProviderId.docx",
ArtifactsDir + u"DocumentBuilder.SignatureLineProviderId.Signed.docx", certHolder, signOptions);
// Re-open our saved document, and verify that the "IsSigned" and "IsValid" properties both equal "true",
// indicating that the signature line contains a signature.
doc = MakeObject<Document>(ArtifactsDir + u"DocumentBuilder.SignatureLineProviderId.Signed.docx");
auto shape = System::DynamicCast<Shape>(doc->GetChild(NodeType::Shape, 0, true));
signatureLine = shape->get_SignatureLine();
ASSERT_TRUE(signatureLine->get_IsSigned());
ASSERT_TRUE(signatureLine->get_IsValid());

◆ InsertSignatureLine() [2/2]

System::SharedPtr<Aspose::Words::Drawing::Shape> Aspose::Words::DocumentBuilder::InsertSignatureLine ( const System::SharedPtr< Aspose::Words::SignatureLineOptions > &  signatureLineOptions,
Aspose::Words::Drawing::RelativeHorizontalPosition  horzPos,
double  left,
Aspose::Words::Drawing::RelativeVerticalPosition  vertPos,
double  top,
Aspose::Words::Drawing::WrapType  wrapType 
)

Inserts a signature line at the specified position.

You can change the image size, location, positioning method and other settings using the Shape object returned by this method.

Parameters
signatureLineOptionsThe object that stores parameters of creating signature line.
horzPosSpecifies where the distance to the signature line is measured from.
leftDistance in points from the origin to the left side of the signature line.
vertPosSpecifies where the distance to the signature line measured from.
topDistance in points from the origin to the top side of the signature line.
wrapTypeSpecifies how to wrap text around the signature line.
Returns
The signature line node that was just inserted.
Examples

Shows how to insert an inline signature line into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
auto options = MakeObject<SignatureLineOptions>();
options->set_Signer(u"John Doe");
options->set_SignerTitle(u"Manager");
options->set_Email(u"johndoe@aspose.com");
options->set_ShowDate(true);
options->set_DefaultInstructions(false);
options->set_Instructions(u"Please sign here.");
options->set_AllowComments(true);
builder->InsertSignatureLine(options, RelativeHorizontalPosition::RightMargin, 2.0, RelativeVerticalPosition::Page, 3.0, WrapType::Inline);
// The signature line can be signed in Microsoft Word by double clicking it.
doc->Save(ArtifactsDir + u"DocumentBuilder.SignatureLineInline.docx");

◆ InsertStyleSeparator()

void Aspose::Words::DocumentBuilder::InsertStyleSeparator ( )

Inserts style separator into the document.

Examples

Shows how to work with style separators.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Each paragraph can only have one style.
// The InsertStyleSeparator method allows us to work around this limitation.
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Write(u"This text is in a Heading style. ");
builder->InsertStyleSeparator();
SharedPtr<Style> paraStyle = builder->get_Document()->get_Styles()->Add(StyleType::Paragraph, u"MyParaStyle");
paraStyle->get_Font()->set_Bold(false);
paraStyle->get_Font()->set_Size(8);
paraStyle->get_Font()->set_Name(u"Arial");
builder->get_ParagraphFormat()->set_StyleName(paraStyle->get_Name());
builder->Write(u"This text is in a custom style. ");
// Calling the InsertStyleSeparator method creates another paragraph,
// which can have a different style to the previous. There will be no break between paragraphs.
// The text in the output document will look like one paragraph with two styles.
ASSERT_EQ(2, doc->get_FirstSection()->get_Body()->get_Paragraphs()->get_Count());
ASSERT_EQ(u"Heading 1", doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(0)->get_ParagraphFormat()->get_Style()->get_Name());
ASSERT_EQ(u"MyParaStyle", doc->get_FirstSection()->get_Body()->get_Paragraphs()->idx_get(1)->get_ParagraphFormat()->get_Style()->get_Name());
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertStyleSeparator.docx");

◆ InsertTableOfContents()

System::SharedPtr<Aspose::Words::Fields::Field> Aspose::Words::DocumentBuilder::InsertTableOfContents ( const System::String switches)

Inserts a TOC (table of contents) field into the document.

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.

Parameters
switchesThe TOC field switches.
Examples

Shows how to insert a Table of contents (TOC) into a document using heading styles as entries.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a table of contents for the first page of the document.
// Configure the table to pick up paragraphs with headings of levels 1 to 3.
// Also, set its entries to be hyperlinks that will take us
// to the location of the heading when left-clicked in Microsoft Word.
builder->InsertTableOfContents(u"\\o \"1-3\" \\h \\z \\u");
builder->InsertBreak(BreakType::PageBreak);
// Populate the table of contents by adding paragraphs with heading styles.
// Each such heading with a level between 1 and 3 will create an entry in the table.
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 1.1");
builder->Writeln(u"Heading 1.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Writeln(u"Heading 2");
builder->Writeln(u"Heading 3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.1");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading3);
builder->Writeln(u"Heading 3.1.1");
builder->Writeln(u"Heading 3.1.2");
builder->Writeln(u"Heading 3.1.3");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading4);
builder->Writeln(u"Heading 3.1.3.1");
builder->Writeln(u"Heading 3.1.3.2");
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading2);
builder->Writeln(u"Heading 3.2");
builder->Writeln(u"Heading 3.3");
// A table of contents is a field of a type that needs to be updated to show an up-to-date result.
doc->UpdateFields();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertToc.docx");

◆ InsertTextInput()

System::SharedPtr<Aspose::Words::Fields::FormField> Aspose::Words::DocumentBuilder::InsertTextInput ( const System::String name,
Aspose::Words::Fields::TextFormFieldType  type,
const System::String format,
const System::String fieldValue,
int32_t  maxLength 
)

Inserts a text form field at the current position.

If you specify a name for the form field, then a bookmark is automatically created with the same name.

Parameters
nameThe name of the form field. Can be an empty string.
typeSpecifies the type of the text form field.
formatFormat string used to format the value of the form field.
fieldValueText that will be shown in the field.
maxLengthMaximum length the user can enter into the form field. Set to zero for unlimited length.
Returns
The form field node that was just inserted.
Examples

Shows how to create form fields.

auto builder = MakeObject<DocumentBuilder>();
// Form fields are objects in the document that the user can interact with by being prompted to enter values.
// We can create them using a document builder, and below are two ways of doing so.
// 1 - Basic text input:
builder->InsertTextInput(u"My text input", TextFormFieldType::Regular, u"", u"Enter your name here", 30);
// 2 - Combo box with prompt text, and a range of possible values:
ArrayPtr<String> items = MakeArray<String>({u"-- Select your favorite footwear --", u"Sneakers", u"Oxfords", u"Flip-flops", u"Other"});
builder->InsertParagraph();
builder->InsertComboBox(u"My combo box", items, 0);
builder->get_Document()->Save(ArtifactsDir + u"DocumentBuilder.CreateForm.docx");

Shows how to insert a text input form field into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a form that prompts the user to enter text.
builder->InsertTextInput(u"TextInput", TextFormFieldType::Regular, u"", u"Enter your text here", 0);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTextInput.docx");

Shows how to insert a text input form field.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Write(u"Please enter text here: ");
// Insert a text input field, which will allow the user to click it and enter text.
// Assign some placeholder text that the user may overwrite and pass
// a maximum text length of 0 to apply no limit on the form field's contents.
builder->InsertTextInput(u"TextInput1", TextFormFieldType::Regular, u"", u"Placeholder text", 0);
// The form field will appear in the form of an "input" html tag, with a type of "text".
doc->Save(ArtifactsDir + u"FormFields.TextInput.html");

◆ Is()

virtual bool Aspose::Words::DocumentBuilder::Is ( const System::TypeInfo target) const
overridevirtual

◆ MoveTo()

void Aspose::Words::DocumentBuilder::MoveTo ( const System::SharedPtr< Aspose::Words::Node > &  node)

Moves the cursor to an inline node or to the end of a paragraph.

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.

Parameters
nodeThe node must be a paragraph or a direct child of a paragraph.
Examples

Shows how to move a document builder's cursor to different nodes in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a valid bookmark, an entity that consists of nodes enclosed by a bookmark start node,
// and a bookmark end node.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
SharedPtr<NodeCollection> firstParagraphNodes = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ChildNodes();
ASSERT_EQ(NodeType::BookmarkStart, firstParagraphNodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Run, firstParagraphNodes->idx_get(1)->get_NodeType());
ASSERT_EQ(u"Bookmark contents.", firstParagraphNodes->idx_get(1)->GetText().Trim());
ASSERT_EQ(NodeType::BookmarkEnd, firstParagraphNodes->idx_get(2)->get_NodeType());
// The document builder's cursor is always ahead of the node that we last added with it.
// If the builder's cursor is at the end of the document, its current node will be null.
// The previous node is the bookmark end node that we last added.
// Adding new nodes with the builder will append them to the last node.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// If we wish to edit a different part of the document with the builder,
// we will need to bring its cursor to the node we wish to edit.
builder->MoveToBookmark(u"MyBookmark");
// Moving it to a bookmark will move it to the first node within the bookmark start and end nodes, the enclosed run.
ASPOSE_ASSERT_EQ(firstParagraphNodes->idx_get(1), builder->get_CurrentNode());
// We can also move the cursor to an individual node like this.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph(), builder->get_CurrentParagraph());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// We can use specific methods to move to the start/end of a document.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

Shows how to move a DocumentBuilder's cursor position to a specified node.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Run 1. ");
// The document builder has a cursor, which acts as the part of the document
// where the builder appends new nodes when we use its document construction methods.
// This cursor functions in the same way as Microsoft Word's blinking cursor,
// and it also always ends up immediately after any node that the builder just inserted.
// To append content to a different part of the document,
// we can move the cursor to a different node with the "MoveTo" method.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_Runs()->idx_get(0));
// The cursor is now in front of the node that we moved it to.
// Adding a second run will insert it in front of the first run.
builder->Writeln(u"Run 2. ");
ASSERT_EQ(u"Run 2. \rRun 1.", doc->GetText().Trim());
// Move the cursor to the end of the document to continue appending text to the end as before.
builder->MoveTo(doc->get_LastSection()->get_Body()->get_LastParagraph());
builder->Writeln(u"Run 3. ");
ASSERT_EQ(u"Run 2. \rRun 1. \rRun 3.", doc->GetText().Trim());

◆ MoveToBookmark() [1/2]

bool Aspose::Words::DocumentBuilder::MoveToBookmark ( const System::String bookmarkName)

Moves the cursor to a bookmark.

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.

Parameters
bookmarkNameThe name of the bookmark to move the cursor to.
Returns
True if the bookmark was found; false otherwise.
Examples

Shows how to move a document builder's cursor to different nodes in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a valid bookmark, an entity that consists of nodes enclosed by a bookmark start node,
// and a bookmark end node.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
SharedPtr<NodeCollection> firstParagraphNodes = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ChildNodes();
ASSERT_EQ(NodeType::BookmarkStart, firstParagraphNodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Run, firstParagraphNodes->idx_get(1)->get_NodeType());
ASSERT_EQ(u"Bookmark contents.", firstParagraphNodes->idx_get(1)->GetText().Trim());
ASSERT_EQ(NodeType::BookmarkEnd, firstParagraphNodes->idx_get(2)->get_NodeType());
// The document builder's cursor is always ahead of the node that we last added with it.
// If the builder's cursor is at the end of the document, its current node will be null.
// The previous node is the bookmark end node that we last added.
// Adding new nodes with the builder will append them to the last node.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// If we wish to edit a different part of the document with the builder,
// we will need to bring its cursor to the node we wish to edit.
builder->MoveToBookmark(u"MyBookmark");
// Moving it to a bookmark will move it to the first node within the bookmark start and end nodes, the enclosed run.
ASPOSE_ASSERT_EQ(firstParagraphNodes->idx_get(1), builder->get_CurrentNode());
// We can also move the cursor to an individual node like this.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph(), builder->get_CurrentParagraph());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// We can use specific methods to move to the start/end of a document.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

◆ MoveToBookmark() [2/2]

bool Aspose::Words::DocumentBuilder::MoveToBookmark ( const System::String bookmarkName,
bool  isStart,
bool  isAfter 
)

Moves the cursor to a bookmark with greater precision.

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.

Parameters
bookmarkNameThe name of the bookmark to move the cursor to.
isStartWhen true, moves the cursor to the beginning of the bookmark. When false, moves the cursor to the end of the bookmark.
isAfterWhen 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.
Returns
True if the bookmark was found; false otherwise.
Examples

Shows how to move a document builder's node insertion point cursor to a bookmark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// A valid bookmark consists of a BookmarkStart node, a BookmarkEnd node with a
// matching bookmark name somewhere afterward, and contents enclosed by those nodes.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Hello world! ");
builder->EndBookmark(u"MyBookmark");
// There are 4 ways of moving a document builder's cursor to a bookmark.
// If we are between the BookmarkStart and BookmarkEnd nodes, the cursor will be inside the bookmark.
// This means that any text added by the builder will become a part of the bookmark.
// 1 - Outside of the bookmark, in front of the BookmarkStart node:
ASSERT_TRUE(builder->MoveToBookmark(u"MyBookmark", true, false));
builder->Write(u"1. ");
ASSERT_EQ(u"Hello world! ", doc->get_Range()->get_Bookmarks()->idx_get(u"MyBookmark")->get_Text());
ASSERT_EQ(u"1. Hello world!", doc->GetText().Trim());
// 2 - Inside the bookmark, right after the BookmarkStart node:
ASSERT_TRUE(builder->MoveToBookmark(u"MyBookmark", true, true));
builder->Write(u"2. ");
ASSERT_EQ(u"2. Hello world! ", doc->get_Range()->get_Bookmarks()->idx_get(u"MyBookmark")->get_Text());
ASSERT_EQ(u"1. 2. Hello world!", doc->GetText().Trim());
// 2 - Inside the bookmark, right in front of the BookmarkEnd node:
ASSERT_TRUE(builder->MoveToBookmark(u"MyBookmark", false, false));
builder->Write(u"3. ");
ASSERT_EQ(u"2. Hello world! 3. ", doc->get_Range()->get_Bookmarks()->idx_get(u"MyBookmark")->get_Text());
ASSERT_EQ(u"1. 2. Hello world! 3.", doc->GetText().Trim());
// 4 - Outside of the bookmark, after the BookmarkEnd node:
ASSERT_TRUE(builder->MoveToBookmark(u"MyBookmark", false, true));
builder->Write(u"4.");
ASSERT_EQ(u"2. Hello world! 3. ", doc->get_Range()->get_Bookmarks()->idx_get(u"MyBookmark")->get_Text());
ASSERT_EQ(u"1. 2. Hello world! 3. 4.", doc->GetText().Trim());

◆ MoveToCell()

void Aspose::Words::DocumentBuilder::MoveToCell ( int32_t  tableIndex,
int32_t  rowIndex,
int32_t  columnIndex,
int32_t  characterIndex 
)

Moves the cursor to a table cell in the current section.

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.

Parameters
tableIndexThe index of the table to move to.
rowIndexThe index of the row in the table.
columnIndexThe index of the column in the table.
characterIndexThe index of the character inside the cell. A negative value allows you to specify a position from the end of the cell. Use -1 to move to the end of the cell.
Examples

Shows how to move a document builder's cursor to a cell in a table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create an empty 2x2 table.
builder->StartTable();
builder->InsertCell();
builder->InsertCell();
builder->EndRow();
builder->InsertCell();
builder->InsertCell();
builder->EndTable();
// Because we have ended the table with the EndTable method,
// the document builder's cursor is currently outside the table.
// This cursor has the same function as Microsoft Word's blinking text cursor.
// It can also be moved to a different location in the document using the builder's MoveTo methods.
// We can move the cursor back inside the table to a specific cell.
builder->MoveToCell(0, 1, 1, 0);
builder->Write(u"Column 2, cell 2.");
doc->Save(ArtifactsDir + u"DocumentBuilder.MoveToCell.docx");

◆ MoveToDocumentEnd()

void Aspose::Words::DocumentBuilder::MoveToDocumentEnd ( )

Moves the cursor to the end of the document.

Examples

Shows how to move a document builder's cursor to different nodes in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a valid bookmark, an entity that consists of nodes enclosed by a bookmark start node,
// and a bookmark end node.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
SharedPtr<NodeCollection> firstParagraphNodes = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ChildNodes();
ASSERT_EQ(NodeType::BookmarkStart, firstParagraphNodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Run, firstParagraphNodes->idx_get(1)->get_NodeType());
ASSERT_EQ(u"Bookmark contents.", firstParagraphNodes->idx_get(1)->GetText().Trim());
ASSERT_EQ(NodeType::BookmarkEnd, firstParagraphNodes->idx_get(2)->get_NodeType());
// The document builder's cursor is always ahead of the node that we last added with it.
// If the builder's cursor is at the end of the document, its current node will be null.
// The previous node is the bookmark end node that we last added.
// Adding new nodes with the builder will append them to the last node.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// If we wish to edit a different part of the document with the builder,
// we will need to bring its cursor to the node we wish to edit.
builder->MoveToBookmark(u"MyBookmark");
// Moving it to a bookmark will move it to the first node within the bookmark start and end nodes, the enclosed run.
ASPOSE_ASSERT_EQ(firstParagraphNodes->idx_get(1), builder->get_CurrentNode());
// We can also move the cursor to an individual node like this.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph(), builder->get_CurrentParagraph());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// We can use specific methods to move to the start/end of a document.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

◆ MoveToDocumentStart()

void Aspose::Words::DocumentBuilder::MoveToDocumentStart ( )

Moves the cursor to the beginning of the document.

Examples

Shows how to move a document builder's cursor to different nodes in a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Create a valid bookmark, an entity that consists of nodes enclosed by a bookmark start node,
// and a bookmark end node.
builder->StartBookmark(u"MyBookmark");
builder->Write(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
SharedPtr<NodeCollection> firstParagraphNodes = doc->get_FirstSection()->get_Body()->get_FirstParagraph()->get_ChildNodes();
ASSERT_EQ(NodeType::BookmarkStart, firstParagraphNodes->idx_get(0)->get_NodeType());
ASSERT_EQ(NodeType::Run, firstParagraphNodes->idx_get(1)->get_NodeType());
ASSERT_EQ(u"Bookmark contents.", firstParagraphNodes->idx_get(1)->GetText().Trim());
ASSERT_EQ(NodeType::BookmarkEnd, firstParagraphNodes->idx_get(2)->get_NodeType());
// The document builder's cursor is always ahead of the node that we last added with it.
// If the builder's cursor is at the end of the document, its current node will be null.
// The previous node is the bookmark end node that we last added.
// Adding new nodes with the builder will append them to the last node.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// If we wish to edit a different part of the document with the builder,
// we will need to bring its cursor to the node we wish to edit.
builder->MoveToBookmark(u"MyBookmark");
// Moving it to a bookmark will move it to the first node within the bookmark start and end nodes, the enclosed run.
ASPOSE_ASSERT_EQ(firstParagraphNodes->idx_get(1), builder->get_CurrentNode());
// We can also move the cursor to an individual node like this.
builder->MoveTo(doc->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASPOSE_ASSERT_EQ(doc->get_FirstSection()->get_Body()->get_FirstParagraph(), builder->get_CurrentParagraph());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// We can use specific methods to move to the start/end of a document.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

◆ MoveToField()

void Aspose::Words::DocumentBuilder::MoveToField ( const System::SharedPtr< Aspose::Words::Fields::Field > &  field,
bool  isAfter 
)

Moves the cursor to a field in the document.

Parameters
fieldThe field to move the cursor to.
isAfterWhen true, moves the cursor to be after the field end. When false, moves the cursor to be before the field start.
Examples

Shows how to move a document builder's node insertion point cursor to a specific field.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert a field using the DocumentBuilder and add a run of text after it.
SharedPtr<Field> field = builder->InsertField(u" AUTHOR \"John Doe\" ");
// The builder's cursor is currently at end of the document.
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
// Move the cursor to the field while specifying whether to place that cursor before or after the field.
builder->MoveToField(field, moveCursorToAfterTheField);
// Note that the cursor is outside of the field in both cases.
// This means that we cannot edit the field using the builder like this.
// To edit a field, we can use the builder's MoveTo method on a field's FieldStart
// or FieldSeparator node to place the cursor inside.
if (moveCursorToAfterTheField)
{
ASSERT_TRUE(builder->get_CurrentNode() == nullptr);
builder->Write(u" Text immediately after the field.");
ASSERT_EQ(u"\u0013 AUTHOR \"John Doe\" \u0014John Doe\u0015 Text immediately after the field.", doc->GetText().Trim());
}
else
{
ASPOSE_ASSERT_EQ(field->get_Start(), builder->get_CurrentNode());
builder->Write(u"Text immediately before the field. ");
ASSERT_EQ(u"Text immediately before the field. \u0013 AUTHOR \"John Doe\" \u0014John Doe\u0015", doc->GetText().Trim());
}

◆ MoveToHeaderFooter()

void Aspose::Words::DocumentBuilder::MoveToHeaderFooter ( Aspose::Words::HeaderFooterType  headerFooterType)

Moves the cursor to the beginning of a header or footer in the current section.

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 DifferentFirstPageHeaderFooter.

If you want to create headers and footers different for even and odd pages, you need to set OddAndEvenPagesHeaderFooter.

Use MoveToSection() to move out of the header into the main text.

Parameters
headerFooterTypeSpecifies the header or footer to move to.
Examples

Shows how to create headers and footers in a document using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Specify that we want different headers and footers for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers, then add three pages to the document to display each header type.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header for the first page");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header for even pages");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header for all other pages");
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page3");
doc->Save(ArtifactsDir + u"DocumentBuilder.HeadersAndFooters.docx");

Shows how to insert an image, and use it as a watermark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert the image into the header so that it will be visible on every page.
SharedPtr<System::Drawing::Image> image = System::Drawing::Image::FromFile(ImageDir + u"Transparent background logo.png");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
SharedPtr<Shape> shape = builder->InsertImage(image);
shape->set_WrapType(WrapType::None);
shape->set_BehindText(true);
// Place the image at the center of the page.
shape->set_RelativeHorizontalPosition(RelativeHorizontalPosition::Page);
shape->set_RelativeVerticalPosition(RelativeVerticalPosition::Page);
shape->set_Left((builder->get_PageSetup()->get_PageWidth() - shape->get_Width()) / 2);
shape->set_Top((builder->get_PageSetup()->get_PageHeight() - shape->get_Height()) / 2);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertWatermark.docx");

◆ MoveToMergeField() [1/2]

bool Aspose::Words::DocumentBuilder::MoveToMergeField ( const System::String fieldName)

Moves the cursor to a position just beyond the specified merge field and removes the merge field.

Note that this method deletes the merge field from the document after moving the cursor.

Parameters
fieldNameThe case-insensitive name of the mail merge field.
Returns
True if the merge field was found and the cursor was moved; false otherwise.
Examples

Shows how to fill MERGEFIELDs with data with a document builder instead of a mail merge.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Insert some MERGEFIELDS, which accept data from columns of the same name in a data source during a mail merge,
// and then fill them manually.
builder->InsertField(u" MERGEFIELD Chairman ");
builder->InsertField(u" MERGEFIELD ChiefFinancialOfficer ");
builder->InsertField(u" MERGEFIELD ChiefTechnologyOfficer ");
builder->MoveToMergeField(u"Chairman");
builder->set_Bold(true);
builder->Writeln(u"John Doe");
builder->MoveToMergeField(u"ChiefFinancialOfficer");
builder->set_Italic(true);
builder->Writeln(u"Jane Doe");
builder->MoveToMergeField(u"ChiefTechnologyOfficer");
builder->set_Italic(true);
builder->Writeln(u"John Bloggs");
doc->Save(ArtifactsDir + u"DocumentBuilder.FillMergeFields.docx");

◆ MoveToMergeField() [2/2]

bool Aspose::Words::DocumentBuilder::MoveToMergeField ( const System::String fieldName,
bool  isAfter,
bool  isDeleteField 
)

Moves the merge field to the specified merge field.

Parameters
fieldNameThe case-insensitive name of the mail merge field.
isAfterWhen true, moves the cursor to be after the field end. When false, moves the cursor to be before the field start.
isDeleteFieldWhen true, deletes the merge field.
Returns
True if the merge field was found and the cursor was moved; false otherwise.
Examples

Shows how to insert fields, and move the document builder's cursor to them.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD MyMergeField1 \\* MERGEFORMAT");
builder->InsertField(u"MERGEFIELD MyMergeField2 \\* MERGEFORMAT");
// Move the cursor to the first MERGEFIELD.
builder->MoveToMergeField(u"MyMergeField1", true, false);
// Note that the cursor is placed immediately after the first MERGEFIELD, and before the second.
ASPOSE_ASSERT_EQ(doc->get_Range()->get_Fields()->idx_get(1)->get_Start(), builder->get_CurrentNode());
ASPOSE_ASSERT_EQ(doc->get_Range()->get_Fields()->idx_get(0)->get_End(), builder->get_CurrentNode()->get_PreviousSibling());
// If we wish to edit the field's field code or contents using the builder,
// its cursor would need to be inside a field.
// To place it inside a field, we would need to call the document builder's MoveTo method
// and pass the field's start or separator node as an argument.
builder->Write(u" Text between our merge fields. ");
doc->Save(ArtifactsDir + u"DocumentBuilder.MergeFields.docx");

◆ MoveToParagraph()

void Aspose::Words::DocumentBuilder::MoveToParagraph ( int32_t  paragraphIndex,
int32_t  characterIndex 
)

Moves the cursor to a paragraph in the current section.

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.

Parameters
paragraphIndexThe index of the paragraph to move to.
characterIndexThe index of the character inside the paragraph. A negative value allows you to specify a position from the end of the paragraph. Use -1 to move to the end of the paragraph.
Examples

Shows how to move a builder's cursor position to a specified paragraph.

auto doc = MakeObject<Document>(MyDir + u"Paragraphs.docx");
SharedPtr<ParagraphCollection> paragraphs = doc->get_FirstSection()->get_Body()->get_Paragraphs();
ASSERT_EQ(22, paragraphs->get_Count());
// Create document builder to edit the document. The builder's cursor,
// which is the point where it will insert new nodes when we call its document construction methods,
// is currently at the beginning of the document.
auto builder = MakeObject<DocumentBuilder>(doc);
ASSERT_EQ(0, paragraphs->IndexOf(builder->get_CurrentParagraph()));
// Move that cursor to a different paragraph will place that cursor in front of that paragraph.
builder->MoveToParagraph(2, 0);
// Any new content that we add will be inserted at that point.
builder->Writeln(u"This is a new third paragraph. ");

◆ MoveToSection()

void Aspose::Words::DocumentBuilder::MoveToSection ( int32_t  sectionIndex)

Moves the cursor to the beginning of the body in a specified section.

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.

Parameters
sectionIndexThe index of the section to move to.
Examples

Shows how to create headers and footers in a document using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Specify that we want different headers and footers for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers, then add three pages to the document to display each header type.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header for the first page");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header for even pages");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header for all other pages");
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page3");
doc->Save(ArtifactsDir + u"DocumentBuilder.HeadersAndFooters.docx");

◆ PopFont()

void Aspose::Words::DocumentBuilder::PopFont ( )

Retrieves character formatting previously saved on the stack.

See also
Aspose::Words::DocumentBuilder::get_Font
Aspose::Words::DocumentBuilder::PushFont
Examples

Shows how to use a document builder's formatting stack.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Set up font formatting, then write the text that goes before the hyperlink.
builder->get_Font()->set_Name(u"Arial");
builder->get_Font()->set_Size(24);
builder->Write(u"To visit Google, hold Ctrl and click ");
// Preserve our current formatting configuration on the stack.
builder->PushFont();
// Alter the builder's current formatting by applying a new style.
builder->get_Font()->set_StyleIdentifier(StyleIdentifier::Hyperlink);
builder->InsertHyperlink(u"here", u"http://www.google.com", false);
ASSERT_EQ(System::Drawing::Color::get_Blue().ToArgb(), builder->get_Font()->get_Color().ToArgb());
ASSERT_EQ(Underline::Single, builder->get_Font()->get_Underline());
// Restore the font formatting that we saved earlier and remove the element from the stack.
builder->PopFont();
ASSERT_EQ(System::Drawing::Color::Empty.ToArgb(), builder->get_Font()->get_Color().ToArgb());
ASSERT_EQ(Underline::None, builder->get_Font()->get_Underline());
builder->Write(u". We hope you enjoyed the example.");
doc->Save(ArtifactsDir + u"DocumentBuilder.PushPopFont.docx");

◆ PushFont()

void Aspose::Words::DocumentBuilder::PushFont ( )

Saves current character formatting onto the stack.

See also
Aspose::Words::DocumentBuilder::get_Font
Aspose::Words::DocumentBuilder::PopFont
Examples

Shows how to use a document builder's formatting stack.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Set up font formatting, then write the text that goes before the hyperlink.
builder->get_Font()->set_Name(u"Arial");
builder->get_Font()->set_Size(24);
builder->Write(u"To visit Google, hold Ctrl and click ");
// Preserve our current formatting configuration on the stack.
builder->PushFont();
// Alter the builder's current formatting by applying a new style.
builder->get_Font()->set_StyleIdentifier(StyleIdentifier::Hyperlink);
builder->InsertHyperlink(u"here", u"http://www.google.com", false);
ASSERT_EQ(System::Drawing::Color::get_Blue().ToArgb(), builder->get_Font()->get_Color().ToArgb());
ASSERT_EQ(Underline::Single, builder->get_Font()->get_Underline());
// Restore the font formatting that we saved earlier and remove the element from the stack.
builder->PopFont();
ASSERT_EQ(System::Drawing::Color::Empty.ToArgb(), builder->get_Font()->get_Color().ToArgb());
ASSERT_EQ(Underline::None, builder->get_Font()->get_Underline());
builder->Write(u". We hope you enjoyed the example.");
doc->Save(ArtifactsDir + u"DocumentBuilder.PushPopFont.docx");

◆ set_Bold()

void Aspose::Words::DocumentBuilder::set_Bold ( bool  value)

◆ set_Document()

void Aspose::Words::DocumentBuilder::set_Document ( const System::SharedPtr< Aspose::Words::Document > &  value)

◆ set_Italic()

void Aspose::Words::DocumentBuilder::set_Italic ( bool  value)

◆ set_Underline()

void Aspose::Words::DocumentBuilder::set_Underline ( Aspose::Words::Underline  value)

◆ StartBookmark()

System::SharedPtr<Aspose::Words::BookmarkStart> Aspose::Words::DocumentBuilder::StartBookmark ( const System::String bookmarkName)

Marks the current position in the document as a bookmark start.

Bookmarks in a document can overlap and span any range. To create a valid bookmark you need to call both StartBookmark() and EndBookmark() with the same bookmarkName parameter.

Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.

Parameters
bookmarkNameName of the bookmark.
Returns
The bookmark start node that was just created.
Examples

Shows how create a bookmark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// A valid bookmark needs to have document body text enclosed by
// BookmarkStart and BookmarkEnd nodes created with a matching bookmark name.
builder->StartBookmark(u"MyBookmark");
builder->Writeln(u"Hello world!");
builder->EndBookmark(u"MyBookmark");
ASSERT_EQ(1, doc->get_Range()->get_Bookmarks()->get_Count());
ASSERT_EQ(u"MyBookmark", doc->get_Range()->get_Bookmarks()->idx_get(0)->get_Name());
ASSERT_EQ(u"Hello world!", doc->get_Range()->get_Bookmarks()->idx_get(0)->get_Text().Trim());

Shows how to insert a hyperlink which references a local bookmark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartBookmark(u"Bookmark1");
builder->Write(u"Bookmarked text. ");
builder->EndBookmark(u"Bookmark1");
builder->Writeln(u"Text outside of the bookmark.");
// Insert a HYPERLINK field that links to the bookmark. We can pass field switches
// to the "InsertHyperlink" method as part of the argument containing the referenced bookmark's name.
builder->get_Font()->set_Color(System::Drawing::Color::get_Blue());
builder->get_Font()->set_Underline(Underline::Single);
builder->InsertHyperlink(u"Link to Bookmark1", u"Bookmark1\" \\o \"Hyperlink Tip", true);
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertHyperlinkToLocalBookmark.docx");

◆ StartColumnBookmark()

System::SharedPtr<Aspose::Words::BookmarkStart> Aspose::Words::DocumentBuilder::StartColumnBookmark ( const System::String bookmarkName)

Marks the current position in the document as a column bookmark start. The position must be in a table cell.

A column bookmark covers one or more columns in a range of rows. To create a valid bookmark you need to call both StartColumnBookmark() and EndColumnBookmark() with the same bookmarkName parameter.

Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.

The actual position of the inserted BookmarkStart node may differ from the current document builder position.

Parameters
bookmarkNameName of the bookmark.
Returns
The bookmark start node that was just created.
Examples

Shows how to create a column bookmark.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
builder->InsertCell();
// Cells 1,2,4,5 will be bookmarked.
builder->StartColumnBookmark(u"MyBookmark_1");
// Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.
builder->StartColumnBookmark(u"MyBookmark_1");
builder->StartColumnBookmark(u"BadStartBookmark");
builder->Write(u"Cell 1");
builder->InsertCell();
builder->Write(u"Cell 2");
builder->InsertCell();
builder->Write(u"Cell 3");
builder->EndRow();
builder->InsertCell();
builder->Write(u"Cell 4");
builder->InsertCell();
builder->Write(u"Cell 5");
builder->EndColumnBookmark(u"MyBookmark_1");
builder->EndColumnBookmark(u"MyBookmark_1");
builder->InsertCell();
builder->Write(u"Cell 6");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"Bookmarks.CreateColumnBookmark.docx");

◆ StartEditableRange()

System::SharedPtr<Aspose::Words::EditableRangeStart> Aspose::Words::DocumentBuilder::StartEditableRange ( )

Marks the current position in the document as an editable range start.

Editable range in a document can overlap and span any range. To create a valid editable range you need to call both StartEditableRange and EndEditableRange or EndEditableRange() methods.

Badly formed editable range will be ignored when the document is saved.

Returns
The editable range start node that was just created.
Examples

Shows how to work with an editable range.

auto doc = MakeObject<Document>();
doc->Protect(ProtectionType::ReadOnly, u"MyPassword");
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(String(u"Hello world! Since we have set the document's protection level to read-only,") +
u" we cannot edit this paragraph without the password.");
// Editable ranges allow us to leave parts of protected documents open for editing.
SharedPtr<EditableRangeStart> editableRangeStart = builder->StartEditableRange();
builder->Writeln(u"This paragraph is inside an editable range, and can be edited.");
SharedPtr<EditableRangeEnd> editableRangeEnd = builder->EndEditableRange();
// A well-formed editable range has a start node, and end node.
// These nodes have matching IDs and encompass editable nodes.
SharedPtr<EditableRange> editableRange = editableRangeStart->get_EditableRange();
ASSERT_EQ(editableRangeStart->get_Id(), editableRange->get_Id());
ASSERT_EQ(editableRangeEnd->get_Id(), editableRange->get_Id());
// Different parts of the editable range link to each other.
ASSERT_EQ(editableRangeStart->get_Id(), editableRange->get_EditableRangeStart()->get_Id());
ASSERT_EQ(editableRangeStart->get_Id(), editableRangeEnd->get_EditableRangeStart()->get_Id());
ASSERT_EQ(editableRange->get_Id(), editableRangeStart->get_EditableRange()->get_Id());
ASSERT_EQ(editableRangeEnd->get_Id(), editableRange->get_EditableRangeEnd()->get_Id());
// We can access the node types of each part like this. The editable range itself is not a node,
// but an entity which consists of a start, an end, and their enclosed contents.
ASSERT_EQ(NodeType::EditableRangeStart, editableRangeStart->get_NodeType());
ASSERT_EQ(NodeType::EditableRangeEnd, editableRangeEnd->get_NodeType());
builder->Writeln(u"This paragraph is outside the editable range, and cannot be edited.");
doc->Save(ArtifactsDir + u"EditableRange.CreateAndRemove.docx");
// Remove an editable range. All the nodes that were inside the range will remain intact.
editableRange->Remove();

Shows how to create nested editable ranges.

auto doc = MakeObject<Document>();
doc->Protect(ProtectionType::ReadOnly, u"MyPassword");
auto builder = MakeObject<DocumentBuilder>(doc);
builder->Writeln(String(u"Hello world! Since we have set the document's protection level to read-only, ") +
u"we cannot edit this paragraph without the password.");
// Create two nested editable ranges.
SharedPtr<EditableRangeStart> outerEditableRangeStart = builder->StartEditableRange();
builder->Writeln(u"This paragraph inside the outer editable range and can be edited.");
SharedPtr<EditableRangeStart> innerEditableRangeStart = builder->StartEditableRange();
builder->Writeln(u"This paragraph inside both the outer and inner editable ranges and can be edited.");
// Currently, the document builder's node insertion cursor is in more than one ongoing editable range.
// When we want to end an editable range in this situation,
// we need to specify which of the ranges we wish to end by passing its EditableRangeStart node.
builder->EndEditableRange(innerEditableRangeStart);
builder->Writeln(u"This paragraph inside the outer editable range and can be edited.");
builder->EndEditableRange(outerEditableRangeStart);
builder->Writeln(u"This paragraph is outside any editable ranges, and cannot be edited.");
// If a region of text has two overlapping editable ranges with specified groups,
// the combined group of users excluded by both groups are prevented from editing it.
outerEditableRangeStart->get_EditableRange()->set_EditorGroup(EditorType::Everyone);
innerEditableRangeStart->get_EditableRange()->set_EditorGroup(EditorType::Contributors);
doc->Save(ArtifactsDir + u"EditableRange.Nested.docx");

◆ StartTable()

System::SharedPtr<Aspose::Words::Tables::Table> Aspose::Words::DocumentBuilder::StartTable ( )

Starts a table in the document.

The next method to call is InsertCell.

This method starts a nested table when called inside a cell.

Returns
The table node that was just created.
Examples

Shows how to build a table with custom borders.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->ClearFormatting();
builder->get_CellFormat()->set_Width(150);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_GreenYellow());
builder->get_CellFormat()->set_WrapText(false);
builder->get_CellFormat()->set_FitText(true);
builder->get_RowFormat()->ClearFormatting();
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_RowFormat()->set_Height(50);
builder->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::Engrave3D);
builder->get_RowFormat()->get_Borders()->set_Color(System::Drawing::Color::get_Orange());
builder->InsertCell();
builder->Write(u"Row 1, Col 1");
builder->InsertCell();
builder->Write(u"Row 1, Col 2");
builder->EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder->get_CellFormat()->get_Shading()->ClearFormatting();
builder->InsertCell();
builder->Write(u"Row 2, Col 1");
builder->InsertCell();
builder->Write(u"Row 2, Col 2");
builder->EndRow();
// Increase row height to fit the vertical text.
builder->InsertCell();
builder->get_RowFormat()->set_Height(150);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 3, Col 1");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 3, Col 2");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTable.docx");

Shows how to build a formatted 2x2 table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"Row 1, cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
// While building the table, the document builder will apply its current RowFormat/CellFormat property values
// to the current row/cell that its cursor is in and any new rows/cells as it creates them.
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(0)->get_CellFormat()->get_VerticalAlignment());
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(1)->get_CellFormat()->get_VerticalAlignment());
builder->InsertCell();
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 2, cell 1.");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 2, cell 2.");
builder->EndRow();
builder->EndTable();
// Previously added rows and cells are not retroactively affected by changes to the builder's formatting.
ASPOSE_ASSERT_EQ(0, table->get_Rows()->idx_get(0)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Auto, table->get_Rows()->idx_get(0)->get_RowFormat()->get_HeightRule());
ASPOSE_ASSERT_EQ(100, table->get_Rows()->idx_get(1)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Exactly, table->get_Rows()->idx_get(1)->get_RowFormat()->get_HeightRule());
ASSERT_EQ(TextOrientation::Upward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(0)->get_CellFormat()->get_Orientation());
ASSERT_EQ(TextOrientation::Downward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(1)->get_CellFormat()->get_Orientation());
doc->Save(ArtifactsDir + u"DocumentBuilder.BuildTable.docx");

Shows how to format cells with a document builder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, cell 1.");
// Insert a second cell, and then configure cell text padding options.
// The builder will apply these settings at its current cell, and any new cells creates afterwards.
builder->InsertCell();
SharedPtr<CellFormat> cellFormat = builder->get_CellFormat();
cellFormat->set_Width(250);
cellFormat->set_LeftPadding(30);
cellFormat->set_RightPadding(30);
cellFormat->set_TopPadding(30);
cellFormat->set_BottomPadding(30);
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
builder->EndTable();
// The first cell was unaffected by the padding reconfiguration, and still holds the default values.
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_Width());
ASPOSE_ASSERT_EQ(5.4, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_LeftPadding());
ASPOSE_ASSERT_EQ(5.4, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_RightPadding());
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_TopPadding());
ASPOSE_ASSERT_EQ(0.0, table->get_FirstRow()->get_Cells()->idx_get(0)->get_CellFormat()->get_BottomPadding());
ASPOSE_ASSERT_EQ(250.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_Width());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_LeftPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_RightPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_TopPadding());
ASPOSE_ASSERT_EQ(30.0, table->get_FirstRow()->get_Cells()->idx_get(1)->get_CellFormat()->get_BottomPadding());
// The first cell will still grow in the output document to match the size of its neighboring cell.
doc->Save(ArtifactsDir + u"DocumentBuilder.SetCellFormatting.docx");

◆ Type()

static const System::TypeInfo& Aspose::Words::DocumentBuilder::Type ( )
static

◆ Write()

void Aspose::Words::DocumentBuilder::Write ( const System::String text)

Inserts a string into the document at the current insert position.

Parameters
textThe string to insert into the document.
Examples

Shows how to insert a string surrounded by a border into a document.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->get_Font()->get_Border()->set_Color(System::Drawing::Color::get_Green());
builder->get_Font()->get_Border()->set_LineWidth(2.5);
builder->get_Font()->get_Border()->set_LineStyle(LineStyle::DashDotStroker);
builder->Write(u"Text surrounded by green border.");
doc->Save(ArtifactsDir + u"Border.FontBorder.docx");

Shows how to build a table with custom borders.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
builder->StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder->get_ParagraphFormat()->set_Alignment(ParagraphAlignment::Center);
builder->get_CellFormat()->ClearFormatting();
builder->get_CellFormat()->set_Width(150);
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_GreenYellow());
builder->get_CellFormat()->set_WrapText(false);
builder->get_CellFormat()->set_FitText(true);
builder->get_RowFormat()->ClearFormatting();
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_RowFormat()->set_Height(50);
builder->get_RowFormat()->get_Borders()->set_LineStyle(LineStyle::Engrave3D);
builder->get_RowFormat()->get_Borders()->set_Color(System::Drawing::Color::get_Orange());
builder->InsertCell();
builder->Write(u"Row 1, Col 1");
builder->InsertCell();
builder->Write(u"Row 1, Col 2");
builder->EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder->get_CellFormat()->get_Shading()->ClearFormatting();
builder->InsertCell();
builder->Write(u"Row 2, Col 1");
builder->InsertCell();
builder->Write(u"Row 2, Col 2");
builder->EndRow();
// Increase row height to fit the vertical text.
builder->InsertCell();
builder->get_RowFormat()->set_Height(150);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 3, Col 1");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 3, Col 2");
builder->EndRow();
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.InsertTable.docx");

Shows how to use a document builder to create a table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Start the table, then populate the first row with two cells.
builder->StartTable();
builder->InsertCell();
builder->Write(u"Row 1, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, Cell 2.");
// Call the builder's "EndRow" method to start a new row.
builder->EndRow();
builder->InsertCell();
builder->Write(u"Row 2, Cell 1.");
builder->InsertCell();
builder->Write(u"Row 2, Cell 2.");
builder->EndTable();
doc->Save(ArtifactsDir + u"DocumentBuilder.CreateTable.docx");

Shows how to build a formatted 2x2 table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"Row 1, cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
// While building the table, the document builder will apply its current RowFormat/CellFormat property values
// to the current row/cell that its cursor is in and any new rows/cells as it creates them.
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(0)->get_CellFormat()->get_VerticalAlignment());
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(1)->get_CellFormat()->get_VerticalAlignment());
builder->InsertCell();
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 2, cell 1.");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 2, cell 2.");
builder->EndRow();
builder->EndTable();
// Previously added rows and cells are not retroactively affected by changes to the builder's formatting.
ASPOSE_ASSERT_EQ(0, table->get_Rows()->idx_get(0)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Auto, table->get_Rows()->idx_get(0)->get_RowFormat()->get_HeightRule());
ASPOSE_ASSERT_EQ(100, table->get_Rows()->idx_get(1)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Exactly, table->get_Rows()->idx_get(1)->get_RowFormat()->get_HeightRule());
ASSERT_EQ(TextOrientation::Upward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(0)->get_CellFormat()->get_Orientation());
ASSERT_EQ(TextOrientation::Downward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(1)->get_CellFormat()->get_Orientation());
doc->Save(ArtifactsDir + u"DocumentBuilder.BuildTable.docx");

◆ Writeln() [1/2]

void Aspose::Words::DocumentBuilder::Writeln ( )

Inserts a paragraph break into the document.

Calls InsertParagraph.

◆ Writeln() [2/2]

void Aspose::Words::DocumentBuilder::Writeln ( const System::String text)

Inserts a string and a paragraph break into the document.

Parameters
textThe string to insert into the document.
Examples

Shows how to create headers and footers in a document using DocumentBuilder.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
// Specify that we want different headers and footers for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers, then add three pages to the document to display each header type.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header for the first page");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header for even pages");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header for all other pages");
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page3");
doc->Save(ArtifactsDir + u"DocumentBuilder.HeadersAndFooters.docx");

Shows how to build a formatted 2x2 table.

auto doc = MakeObject<Document>();
auto builder = MakeObject<DocumentBuilder>(doc);
SharedPtr<Table> table = builder->StartTable();
builder->InsertCell();
builder->get_CellFormat()->set_VerticalAlignment(CellVerticalAlignment::Center);
builder->Write(u"Row 1, cell 1.");
builder->InsertCell();
builder->Write(u"Row 1, cell 2.");
builder->EndRow();
// While building the table, the document builder will apply its current RowFormat/CellFormat property values
// to the current row/cell that its cursor is in and any new rows/cells as it creates them.
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(0)->get_CellFormat()->get_VerticalAlignment());
ASSERT_EQ(CellVerticalAlignment::Center, table->get_Rows()->idx_get(0)->get_Cells()->idx_get(1)->get_CellFormat()->get_VerticalAlignment());
builder->InsertCell();
builder->get_RowFormat()->set_Height(100);
builder->get_RowFormat()->set_HeightRule(HeightRule::Exactly);
builder->get_CellFormat()->set_Orientation(TextOrientation::Upward);
builder->Write(u"Row 2, cell 1.");
builder->InsertCell();
builder->get_CellFormat()->set_Orientation(TextOrientation::Downward);
builder->Write(u"Row 2, cell 2.");
builder->EndRow();
builder->EndTable();
// Previously added rows and cells are not retroactively affected by changes to the builder's formatting.
ASPOSE_ASSERT_EQ(0, table->get_Rows()->idx_get(0)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Auto, table->get_Rows()->idx_get(0)->get_RowFormat()->get_HeightRule());
ASPOSE_ASSERT_EQ(100, table->get_Rows()->idx_get(1)->get_RowFormat()->get_Height());
ASSERT_EQ(HeightRule::Exactly, table->get_Rows()->idx_get(1)->get_RowFormat()->get_HeightRule());
ASSERT_EQ(TextOrientation::Upward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(0)->get_CellFormat()->get_Orientation());
ASSERT_EQ(TextOrientation::Downward, table->get_Rows()->idx_get(1)->get_Cells()->idx_get(1)->get_CellFormat()->get_Orientation());
doc->Save(ArtifactsDir + u"DocumentBuilder.BuildTable.docx");