public void InsertTableUsingNodeConstructors()
{
//ExStart
//ExFor:Table
//ExFor:Row
//ExFor:Row.RowFormat
//ExFor:RowFormat
//ExFor:Cell
//ExFor:Cell.CellFormat
//ExFor:CellFormat
//ExFor:CellFormat.Shading
//ExFor:Cell.FirstParagraph
//ExId:InsertTableUsingNodeConstructors
//ExSummary:Shows how to insert a table using the constructors of nodes.
Document doc = new Document();
// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.FirstSection.Body.AppendChild(table);
// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.
// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorthim for example.
Row row = new Row(doc);
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);
// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;
// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text"));
// Add the cell to the row.
row.AppendChild(cell);
// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));
doc.Save(MyDir + @"\Artifacts\Table.InsertTableUsingNodes.doc");
//ExEnd
Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count);
Assert.AreEqual(1, doc.GetChildNodes(NodeType.Row, true).Count);
Assert.AreEqual(2, doc.GetChildNodes(NodeType.Cell, true).Count);
Assert.AreEqual("Row 1, Cell 1 Text\r\nRow 1, Cell 2 Text", doc.FirstSection.Body.Tables[0].ToString(SaveFormat.Text).Trim());
}