Products Technologies Demo Docs Blog Support Company

Document Editor: Useful JavaScript Functions for Tables

This article shows how to use JavaScript functions to manipulate tables in the Document Editor. It demonstrates how to set and get text in a table cell, and how to export a table to JSON.

Document Editor: Useful JavaScript Functions for Tables

The JavaScript API of the Document Editor provides a set of methods and events to interact with the document and to manipulate the document content. Some functionality, such as setting the text in a particular table cell, requires different methods and callbacks.

For example, to set the text of a specific cell in a table, you would need to get the specific table and then set the text to a specific cell in the table.

To demonstrate how to set the text of a specific cell in a table, we will first insert a table into the document. The following code snippet shows how to insert a table into the document.

TXTextControl.tables.add(rows, columns, tableId);

Set TableCell Text

After inserting the table, you can set the text of a specific cell in the table by using the following code snippet:

function setTableCellText(tableId, row, column, text) {
    TXTextControl.tables.getItem(table => {
        table.cells.getItem(cell => {
            cell.setText(text);
        }, null, row, column);
    }, null, tableId);
}

The code retrieves the table using the getItem method that accepts an id and returns the table.

The following code calls the above method and sets the text of the first cell in the third row of the table:

setTableCellText(10,3,1,'Hi there!')

Tables in TX Text Control

Get TableCell Text

To get the text of a specific cell in a table, you can use the following code snippet:

async function getTableCellText(tableId, row, column) {
    return new Promise((resolve, reject) => {
        TXTextControl.tables.getItem(table => {
            table.cells.getItem(cell => {
                cell.getText(cellText => {
                    resolve(cellText);
                }, error => {
                    reject(error);
                });
            }, null, row, column);
        }, null, tableId);
    });
}

This asynchronous method retrieves the table using the getItem method that accepts an id and returns the table and uses the getText method to get the text of the cell.

This is how the above method is called:

let text = await getTableCellText(10, 3, 3);

Exporting the Table to JSON

For specific scenarios, it might be necessary to export the table to JSON. The following code snippet shows how to export the table to JSON including text, row, and column information:

async function exportTableAsJSON(tableId) {

    function CustomTableCell(text, row, column) {
        this.text = text;
        this.row = row;
        this.column = column;
    }

    return new Promise((resolve, reject) => {
        TXTextControl.tables.getItem(table => {
            table.rows.getCount(rows => {
                let tableCell = [];

                table.columns.getCount(columns => {
                    let totalCells = rows * columns;

                    for (let i = 1; i <= rows; i++) {
                        for (let j = 1; j <= columns; j++) {
                            table.cells.getItem(cell => {
                                cell.getText(cellText => {
                                    tableCell.push(new CustomTableCell(cellText, i, j));
                                    if (tableCell.length === totalCells) {
                                        resolve(JSON.stringify(tableCell));
                                    }
                                });
                            }, null, i, j);
                        }
                    }

                });
            });
        }, null, tableId);
    });
}

This asynchronous method loops through the specified table and creates a CustomTableCell object of each cell, which is stored in an array that is returned as JSON. It is called as follows:

let tableCell = await exportTableAsJSON(10);
console.log(tableCell);

This is the (shortened) JSON output:

[
   {
      "text":"Cell text 1 1",
      "row":1,
      "column":1
   },
   {
      "text":"Cell text 1 2",
      "row":1,
      "column":2
   },
   {
      "text":"Cell text 1 3",
      "row":1,
      "column":3
   },
   [...]
]

Importing the Table from JSON

After exporting the table to JSON, you can import the table back into the document. The following code snippet shows how to import the table from JSON:

async function importTableFromJSON(tableId, json) {
    return new Promise((resolve, reject) => {
        let tableCell = JSON.parse(json);

        TXTextControl.tables.getItem(table => {
            tableCell.forEach(cell => {
                table.cells.getItem(cellItem => {
                    cellItem.setText(cell.text);
                }, null, cell.row, cell.column);
            });
        }, null, tableId);
    });
}

This asynchronous method accepts the JSON string and loops through the JSON array to add the content to an existing table. In this case, the table with the specific structure must already exist in the document.

If you want to create a new table from the JSON data, you can use the following code snippet:

async function importAndCreateTableFromJSON(tableId, json) {
    return new Promise((resolve, reject) => {
        let tableCell = JSON.parse(json);
        let columns = 0;
        let rows = 0;

        tableCell.forEach(cell => {
            if (cell.column > columns) {
                columns = cell.column;
            }

            if (cell.row > rows) {
                rows = cell.row;
            }
        });

        TXTextControl.tables.add(rows, columns, tableId);

        TXTextControl.tables.getItem(table => {
            tableCell.forEach(cell => {
                table.cells.getItem(cellItem => {
                    cellItem.setText(cell.text);
                }, null, cell.row, cell.column);
            });
        }, null, tableId);
    });
}

Conclusion

This article showed how to set and get the text of a specific cell in a table using the JavaScript API of the Document Editor. Additionally, it showed how to export the table to JSON and import the table from JSON.

These methods can be used to manipulate the content of tables in a document and to export and import tables to and from JSON.

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.NETJavaScriptWindows Forms

Auto-Sizing Tables Proportionally

This article shows how to resize a table to fit the complete page by adjusting each column proportionally.


ASP.NETJavaScriptASP.NET Core

Add JavaScript to PDFs with TX Text Control in C# .NET: Time-Based Alerts…

In this article, we explore how to enrich PDF documents with JavaScript using TX Text Control in C# .NET. Read on to learn how to create time-based alerts that trigger actions based on specific…


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.


ASP.NETWindows FormsASP.NET Core

Splitting Tables at Bookmark Positions and Cloning Table Headers

This article shows how to split tables at bookmark positions and how to clone table headers in TX Text Control .NET for Windows Forms and TX Text Control .NET Server.


ASP.NETWindows FormsExcel

Loading and Processing Excel XLSX Spreadsheet Tables into TX Text Control…

TX Text Control provides a powerful API to load and process Excel spreadsheet tables in .NET applications. This article shows how to load an Excel file and process the tables using TX Text Control…