# Creating Advanced Tables in PDF and DOCX Documents with C#

> This article shows how to create advanced tables in PDF and DOCX documents using the TX Text Control .NET for ASP.NET Server component. This article shows how to create tables from scratch, generate tables from data sources, and how to control the layout of tables.

- **Author:** Bjoern Meyer
- **Published:** 2024-09-30
- **Modified:** 2025-11-16
- **Description:** This article shows how to create advanced tables in PDF and DOCX documents using the TX Text Control .NET for ASP.NET Server component. This article shows how to create tables from scratch, generate tables from data sources, and how to control the layout of tables.
- **7 min read** (1347 words)
- **Tags:**
  - ASP.NET
  - ASP.NET Core
  - Angular
  - Tables
  - PDF
  - MailMerge
- **Web URL:** https://www.textcontrol.com/blog/2024/09/30/creating-advanced-tables-in-pdf-and-docx-documents-with-csharp/
- **LLMs URL:** https://www.textcontrol.com/blog/2024/09/30/creating-advanced-tables-in-pdf-and-docx-documents-with-csharp/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2024/09/30/creating-advanced-tables-in-pdf-and-docx-documents-with-csharp/llms-full.txt

---

Tables are important in documents because they organize information in a clear and concise manner, making it easier to compare data and identify patterns. They enable quick understanding by presenting complex details in rows and columns, which improves readability and accessibility. Key benefits of using tables include better data visualization, the ability to summarize large amounts of information, and improved structure that helps readers focus on key insights without being overwhelmed by text.

TX Text Control makes it easy to create documents with tables, including full control over the layout, text flow, and complexity of the table. Tables can be inserted from scratch or created from data such as JSON or IEnumerable objects.

This article will provide a comprehensive guide on how to create tables in documents using TX Text Control and will cover the following topics:

- Creating a table from scratch
- Inserting a table from JSON data
- Customizing table layout and design
- Adding nested tables and merging cells
- Pagination and text flow in tables

#### Getting Started

To get started with creating tables in documents using TX Text Control, you will need to have the TX Text Control .NET Server component installed on your development machine. You can download a free trial version from the TX Text Control website and follow the installation instructions provided.

> #### Prerequisites
> 
>  The following tutorial requires a trial version of TX Text Control .NET Server.
> 
> - [Download Trial Version](https://www.textcontrol.com/product/tx-text-control-dotnet-server/download/)

1. In Visual Studio, create a new *Console App* using .NET 8.
2. In the *Solution Explorer*, select your created project and choose *Manage NuGet Packages...* from the *Project* main menu.
    
    Select *Text Control Offline Packages* from the *Package source* drop-down.
    
    Install the latest versions of the following package:
    
    
    - TXTextControl.TextControl.ASP.SDK
    
    ![Create PDF](https://s1-www.textcontrol.com/assets/dist/blog/2024/09/30/a/assets/step1.webp "Create PDF")

### Creating Tables Programmatically

TX Text Control provides a powerful API for creating tables programmatically in documents. You can define the number of rows and columns, set the border style, background color, and text alignment for each cell, and customize the layout and design of the table to suit your requirements.

The following code inserts a five-column, five-row table and sets the first row as the table header. It also sets the format of the cells and the cell text.

```
using TXTextControl;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    tx.Tables.Add(5, 5, 10);

    Table table = tx.Tables.GetItem(10);

    // set and format the header row
    table.Rows[1].IsHeader = true;
    table.Rows[1].CellFormat = new TableCellFormat() {
        BackColor = System.Drawing.Color.LightGray,
        BottomBorderWidth = 10,
    };

    // set the cell text and format the cells
    foreach (TableCell cell in table.Cells) {
        if (table.Rows[cell.Row].IsHeader) { // header row
            cell.Text = "Header Column " + cell.Column.ToString();
        }
        else { // data rows
            cell.Text = "Row " + cell.Row.ToString() + ", Column " + cell.Column.ToString();

            cell.CellFormat = new TableCellFormat()
            {
                BottomBorderWidth = 1,
                TopBorderWidth = 1,
                LeftBorderWidth = 1,
                RightBorderWidth = 1
            };
        }
    }

    // save the document as PDF
    tx.Save("results.pdf", StreamType.AdobePDF);
}
```

The screenshot below shows the output of the code snippet above, displaying a table with five columns and five rows, where the first row is the table header. The table header is repeated on each page when the table spans multiple pages.

![Tables in TX Text Control](https://s1-www.textcontrol.com/assets/dist/blog/2024/09/30/a/assets/tables1.webp "Tables in TX Text Control")

### Inserting Tables from JSON Data

TX Text Control allows you to insert tables from JSON data, making it easy to populate tables with dynamic content from external sources. Consider the following JSON data representing a list of products:

```
[
  {
    "invoice": "12345",
    "date": "2019-01-01",
    "customer": "John Doe",
    "items": [
      {
        "product": "apple",
        "price": 1.00,
        "quantity": 10
      },
      {
        "product": "banana",
        "price": 0.50,
        "quantity": 20
      },
      {
        "product": "cherry",
        "price": 0.25,
        "quantity": 30
      }
    ]
  }
]
```

Merge fields and repeating blocks can be populated from this JSON data using the MailMerge class. The template can either be designed in advance or dynamically as in this example. The following code loads the JSON file into the DataSourceManager that is used to add merge blocks to a document.

```
using TXTextControl;
using TXTextControl.DocumentServer;
using TXTextControl.DocumentServer.DataSources;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    string jsonData = File.ReadAllText("tabledata.json");

    DataSourceManager dataSourceManager = new DataSourceManager();
    dataSourceManager.LoadJson(jsonData);

    MergeBlockInfo mergeBlockInfo = new MergeBlockInfo("items");
    mergeBlockInfo.ColumnNames.Add("product");
    mergeBlockInfo.ColumnNames.Add("price");
    mergeBlockInfo.ColumnNames.Add("quantity");

    MergeBlockSettings mergeBlockSettings = new MergeBlockSettings(BlockTemplateType.TableRow, true);

    dataSourceManager.InsertMergeBlock(tx, mergeBlockInfo, mergeBlockSettings);

    MailMerge mailMerge = new MailMerge()
    {
        TextComponent = tx
    };

    mailMerge.MergeJsonData(jsonData);

    // save the document as PDF
    tx.Save("results.pdf", StreamType.AdobePDF);
}
```

Finally, the *MailMerge* class is used to merge the same data into the created template structure.

![Tables in TX Text Control](https://s1-www.textcontrol.com/assets/dist/blog/2024/09/30/a/assets/tables2.webp "Tables in TX Text Control")

### Created Nested Tables

TX Text Control allows you to create nested tables within a document, enabling you to organize complex data structures and improve the readability of your documents. Nested tables can be inserted inside other tables in unlimited levels, providing a flexible way to present hierarchical data and relationships.

The following code snippet demonstrates how to create a nested table inside a parent table using TX Text Control:

```
using TXTextControl;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    // reusing the table cell format
    TableCellFormat tableCellFormat = new TableCellFormat()
    {
        BottomBorderWidth = 1,
        TopBorderWidth = 1,
        LeftBorderWidth = 1,
        RightBorderWidth = 1
    };

    // add a table
    tx.Tables.Add(5, 5, 10);

    Table table = tx.Tables.GetItem(10);

    // select first cell
    table.Cells[1, 1].Select();
    tx.Selection.Length = 0;

    // insert a nested table
    tx.Tables.Add(2, 2);

    // set text in nested table
    foreach (TableCell cell in table.NestedTables[1].Cells)
    {
        cell.Text = "nested";
        cell.CellFormat = tableCellFormat;
    }

    // set text and format in main table
    foreach (TableCell cell in table.Cells)
    {
        if (cell.Text == "")
            cell.Text = "main";

        cell.CellFormat = tableCellFormat;
    }

    tx.Save("results.pdf", StreamType.AdobePDF);
}
```

The screenshot below shows the output of the code snippet above, displaying a parent table with a nested child table inside one of the cells. The nested table contains two rows and two columns, each with text content.

![Tables in TX Text Control](https://s1-www.textcontrol.com/assets/dist/blog/2024/09/30/a/assets/tables3.webp "Tables in TX Text Control")

### Avoid Page Breaks in Cells

When working with tables in documents, it is important to consider pagination and text flow to ensure that the content is displayed correctly and consistently across pages. TX Text Control provides options to control page breaks within tables, including the ability to prevent page breaks inside cells and ensure that table rows are kept together on the same page.

The following code snippet demonstrates how to avoid page breaks inside table cells and keep rows together on the same page using TX Text Control:

```
using TXTextControl;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    tx.Tables.Add(5, 5, 10);

    Table table = tx.Tables.GetItem(10);

    // set the cell text and format the cells
    foreach (TableCell cell in table.Cells)
    {
        cell.Text = "Row " + cell.Row.ToString() + ", Column " + cell.Column.ToString();

        cell.CellFormat = new TableCellFormat()
        {
            BottomBorderWidth = 1,
            TopBorderWidth = 1,
            LeftBorderWidth = 1,
            RightBorderWidth = 1
        };
    }

    table.Rows[5].AllowPageBreak = false;

    string randomLongText = "This is a very long text that should be wrapped to the next line.";

    // create a loop that repeats this text
    for (int i = 0; i < 4; i++)
    {
        randomLongText += " " + randomLongText;
    }

    // add long content to first cell of the last row
    table.Cells[5,1].Text = randomLongText;

    // save the document as PDF
    tx.Save("results.pdf", StreamType.AdobePDF);
}
```

The screenshot below shows the output of the code snippet above, displaying a table with multiple rows and columns where the last row is kept together on the same page without page breaks inside cells.

![Tables in TX Text Control](https://s1-www.textcontrol.com/assets/dist/blog/2024/09/30/a/assets/tables4.webp "Tables in TX Text Control")

In addition, paragraph settings such as *Keep Lines Together* or a setting to define how many lines of a paragraph should be kept together on a page when the table breaks across pages are available.

### Conclusion

Tables are an essential feature of documents that help organize information and improve readability. TX Text Control provides a powerful API for creating tables in documents, including the ability to create tables from scratch, insert tables from JSON data, customize table layout and design, add nested tables, and control pagination and text flow within tables.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Related Posts

- [Use MailMerge in .NET on Linux to Generate Pixel-Perfect PDFs from DOCX Templates](https://www.textcontrol.com/blog/2025/05/27/use-mailmerge-in-dotnet-on-linux-to-generate-pixel-perfect-pdfs-from-docx-templates/llms.txt)
- [Why Table Control in Templates is Important for Professional PDF Creation in C#](https://www.textcontrol.com/blog/2025/04/04/why-table-control-in-templates-is-important-for-professional-pdf-creation/llms.txt)
- [Video Tutorial: Creating a MailMerge Template and JSON Data Structure](https://www.textcontrol.com/blog/2024/08/16/video-tutorial-creating-a-mailmerge-template-and-json-data-structure/llms.txt)
- [How to Choose the Best C# Library for your Document Processing Needs](https://www.textcontrol.com/blog/2023/08/07/how-to-choose-the-best-library-for-your-document-processing-needs/llms.txt)
- [Adding Attachments to Adobe PDF Documents using C#](https://www.textcontrol.com/blog/2022/02/25/adding-attachments-to-adobe-pdf-documents-using-csharp/llms.txt)
- [Using QR Codes in PDF Documents in C# .NET](https://www.textcontrol.com/blog/2026/04/21/using-qr-codes-in-pdf-documents-in-csharp-dotnet/llms.txt)
- [Why Structured E-Invoices Still Need Tamper Protection using C# and .NET](https://www.textcontrol.com/blog/2026/03/24/why-structured-e-invoices-still-need-tamper-protection-using-csharp-and-dotnet/llms.txt)
- [Create Fillable PDFs from HTML Forms in C# ASP.NET Core Using a WYSIWYG Template](https://www.textcontrol.com/blog/2026/03/17/create-fillable-pdfs-from-html-forms-in-csharp-aspnet-core-using-a-wysiwyg-template/llms.txt)
- [Why HTML to PDF Conversion is Often the Wrong Choice for Business Documents in C# .NET](https://www.textcontrol.com/blog/2026/03/13/why-html-to-pdf-conversion-is-often-the-wrong-choice-for-business-documents-in-csharp-dot-net/llms.txt)
- [Convert CSV to PDF in .NET C#](https://www.textcontrol.com/blog/2026/01/19/convert-csv-to-pdf-in-dotnet-csharp/llms.txt)
- [A Complete Guide to Converting Markdown to PDF in .NET C#](https://www.textcontrol.com/blog/2026/01/07/a-complete-guide-to-converting-markdown-to-pdf-in-dotnet-csharp/llms.txt)
- [Why PDF Creation Belongs at the End of the Business Process](https://www.textcontrol.com/blog/2026/01/02/why-pdf-creation-belongs-at-the-end-of-the-business-process/llms.txt)
- [Designing the Perfect PDF Form with TX Text Control in .NET C#](https://www.textcontrol.com/blog/2025/12/16/designing-the-perfect-pdf-form-with-tx-text-control-in-dotnet-csharp/llms.txt)
- [Why Defining MIME Types for PDF/A Attachments Is Essential](https://www.textcontrol.com/blog/2025/12/10/why-defining-mime-types-for-pdfa-attachments-is-essential/llms.txt)
- [Validate Digital Signatures and the Integrity of PDF Documents in C# .NET](https://www.textcontrol.com/blog/2025/11/14/validate-digital-signatures-and-the-integrity-of-pdf-documents-in-csharp-dotnet/llms.txt)
- [Validate PDF/UA Documents and Verify Electronic Signatures in C# .NET](https://www.textcontrol.com/blog/2025/11/13/validate-pdf-ua-documents-and-verify-electronic-signatures-in-csharp-dotnet/llms.txt)
- [How To Choose the Right C# PDF Generation Library: Developer Checklist](https://www.textcontrol.com/blog/2025/11/12/how-to-choose-the-right-csharp-pdf-generation-library-developer-checklist/llms.txt)
- [Why Digitally Signing your PDFs is the Only Reliable Way to Prevent Tampering](https://www.textcontrol.com/blog/2025/10/30/why-digitally-signing-your-pdfs-is-the-only-reliable-way-to-prevent-tampering/llms.txt)
- [Automating PDF/UA Accessibility with AI: Describing DOCX Documents Using TX Text Control and LLMs](https://www.textcontrol.com/blog/2025/10/16/automating-pdf-ua-accessibility-with-ai-describing-docx-documents-using-tx-text-control-and-llms/llms.txt)
- [Converting Office Open XML (DOCX) to PDF in Java](https://www.textcontrol.com/blog/2025/10/14/converting-office-open-xml-docx-to-pdf-in-java/llms.txt)
- [Extending DS Server with Custom Digital Signature APIs](https://www.textcontrol.com/blog/2025/10/09/extending-ds-server-with-custom-digital-signature-apis/llms.txt)
- [Why PDF/UA and PDF/A-3a Matter: Accessibility, Archiving, and Legal Compliance](https://www.textcontrol.com/blog/2025/10/07/why-pdf-ua-and-pdf-a-3a-matter-accessibility-archiving-and-legal-compliance/llms.txt)
- [Convert Markdown to PDF in a Console Application on Linux and Windows](https://www.textcontrol.com/blog/2025/09/23/convert-markdown-to-pdf-in-a-console-application-on-linux-and-windows/llms.txt)
- [Mining PDFs with Regex in C#: Practical Patterns, Tips, and Ideas](https://www.textcontrol.com/blog/2025/08/12/mining-pdfs-with-regex-in-csharp-practical-patterns-tips-and-ideas/llms.txt)
- [Streamline Data Collection with Embedded Forms in C# .NET](https://www.textcontrol.com/blog/2025/08/02/streamline-data-collection-with-embedded-forms-in-csharp-dotnet/llms.txt)
