Products Technologies Demo Docs Blog Support Company

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.

Creating Advanced Tables in PDF and DOCX Documents with C#

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.

  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

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

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

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

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

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.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETASP.NET CoreDOCX

Use MailMerge in .NET on Linux to Generate Pixel-Perfect PDFs from DOCX…

This article explores how to use the TX Text Control MailMerge feature in .NET applications on Linux to generate pixel-perfect PDFs from DOCX templates. This powerful combination enables…


ASP.NETASP.NET CorePDF

Why Table Control in Templates is Important for Professional PDF Creation in C#

Controlling how tables behave at page breaks is an important factor in creating professional-looking documents. This article discusses the importance of table control in templates for PDF generation.


AngularASP.NETASP.NET Core

Video Tutorial: Creating a MailMerge Template and JSON Data Structure

This video tutorial shows how to create a MailMerge template and a JSON data structure to merge data into a document. This tutorial will walk you through the steps necessary to create a template…


AngularASP.NETASP.NET Core

How to Choose the Best C# Library for your Document Processing Needs

There are many document processing libraries and components on the market. This article is an overview of all the important aspects in the selection of the best library for your needs.


AngularASP.NETASP.NET Core

Adding Attachments to Adobe PDF Documents using C#

TX Text Control is used to create electronic document containers by embedding files in Adobe PDF documents. This tutorial shows how to add and extract attachments to and from PDF documents.