TX Text Control .NET Server

Text and Paragraph Formatting

Topic

Formatting doesn't have to come from the ribbon. From buttons, templates or rules of your application, the JavaScript API of the Document Editor sets the character formatting of the selection and the formatting of paragraphs, creates numbered and bulleted lists and applies tab stops and formatting styles.

The examples extend the view of the ASP.NET Core tutorial. JavaScript API explains the callbacks that all calls on this page use.

How Formatting Works

Users format text with the Home tab of the ribbon, in its Font, Paragraph and Styles groups:

Home tab of the Document Editor ribbon with the groups Clipboard, Font, Paragraph, Styles and Editing

Your code formats the same text through objects of the JavaScript API:

ObjectFormatsYou get it from
SelectionCharacters: font, size, bold, colors and other attributesTXTextControl.selection
ParagraphFormatParagraphs: alignment, indents, spacing, frames and tab stopsSelection.paragraphFormat
ListFormatNumbered and bulleted listsSelection.listFormat
ParagraphStyle and InlineStyleNamed sets of attributes that you apply to paragraphs or to parts of a paragraphTXTextControl.paragraphStyles and TXTextControl.inlineStyles

The set methods change the selected text, or the selected paragraphs. To select text from code, assign the start position and length to TXTextControl.selection, for example TXTextControl.selection = { start: 0, length: 10 };, or call TXTextControl.select.

Each get method passes the value to a callback. If the selection contains different values, for example two font sizes, a get method such as getFontSize passes the default value of the attribute instead; for different fonts, getFontName passes an empty string.

Most sizes and distances are in twips, 1/20 of a point: 240 twips are 12 points. The font size of the selection is an exception: Selection.setFontSize takes points.

Format Characters

These methods of Selection set character attributes. Each one takes the value, an optional callback and an optional error callback:

MethodValue
setFontNameThe name of the font
setFontSizeThe size in points
setBold, setItalic, setStrikeouttrue or false
setUnderlineA value of FontUnderlineStyle
setForeColor, setTextBackColorA color string, for example "#1F4E79"
setBaselineThe distance from the baseline in twips
setAutoBaselineAutomatic superscript or subscript, a value of AutoBaseline
setCapitalsCapitals or small capitals, a value of Capitals
setCharacterSpacingTwips added to each character; a negative value reduces the spacing
setCharacterScalingThe character width in percent of the average width
setCultureThe language of the text, for example "de-DE", used for spell checking

Other methods change the selection as a whole: growFont and shrinkFont change the font size, changeCapitalization converts the text to upper or lower case, and removeFormatting resets the character attributes to their defaults.

Format Paragraphs

Selection.paragraphFormat returns the formatting of the selected paragraphs. Its set methods include:

MethodSets
setAlignmentThe alignment, a value of HorizontalAlignment: Left, Right, Center or Justify
setLeftIndent, setRightIndent, setHangingIndentThe indents in twips
setTopDistance, setBottomDistanceThe space to the previous and the next paragraph in twips
setLineSpacingThe line spacing in percent of the font size
setAbsoluteLineSpacingA fixed line spacing in twips
setBackColorThe background color
setFrame, setFrameStyle, setFrameLineWidth, setFrameLineColorLines around the paragraph: which lines, single or double, their width in twips and their color
setKeepWithNext, setKeepLinesTogether, setPageBreakBeforeHow the paragraph is split across pages

The following buttons format the selected text and paragraphs. A helper function turns each set method into a promise, so that the calls run one after another, and beginUndoAction and endUndoAction make all changes one undo step. Add the code below the editor in Views/Home/Index.cshtml:

<input type="button" onclick="formatHeading()" value="Format Heading" />
<input type="button" onclick="createNumberedList()" value="Numbered List" />

<script>
    // Calls a set method and waits until the change has been made
    function setAsync(target, method, value) {
        return new Promise(function (resolve, reject) {
            target[method](value, resolve, reject);
        });
    }

    async function formatHeading() {
        var selection = TXTextControl.selection;
        var paragraphFormat = selection.paragraphFormat;

        // Undo all of the following changes in one step
        TXTextControl.beginUndoAction("Format heading");

        // Character formatting of the selected text
        await setAsync(selection, "setFontName", "Arial");
        await setAsync(selection, "setFontSize", 14); // points
        await setAsync(selection, "setBold", true);
        await setAsync(selection, "setForeColor", "#1F4E79");

        // Formatting of the selected paragraphs
        await setAsync(paragraphFormat, "setAlignment", TXTextControl.HorizontalAlignment.Center);
        await setAsync(paragraphFormat, "setBottomDistance", 240); // 240 twips = 12 points

        TXTextControl.endUndoAction();
    }

    async function createNumberedList() {
        var listFormat = TXTextControl.selection.listFormat;

        await setAsync(listFormat, "setType", TXTextControl.ListType.Numbered);
        await setAsync(listFormat, "setNumberFormat", TXTextControl.NumberFormat.CapitalLetters);
        await setAsync(listFormat, "setTextAfterNumber", ")");
    }
</script>

Select a line of text and click Format Heading: the line becomes a centered, bold, blue heading, and Ctrl+Z removes all changes at once. Select several paragraphs and click Numbered List to number them A), B), C).

Create Lists

Selection.listFormat turns the selected paragraphs into a list. setType sets the kind of list with a value of ListType: Bulleted, Numbered, Structured or None. In a structured list, the numbers of the higher levels are shown in front of each number, as in 1.2.3.

Further methods set the details:

Set Tab Stops

Tab stops belong to the paragraph format. setTabPositions takes an array of positions in twips, and setTabTypes an array of the same length with values of TabType: LeftTab, RightTab, CenterTab, DecimalTab or RightBorderTab. setTabLeaders fills the space before a tab stop with dots, dashes or a line, for example in a table of contents.

Users set tab stops in the ruler bar or in the tabs dialog box.

Use Formatting Styles

A formatting style is a named set of formatting attributes. Paragraph styles format complete paragraphs, and inline styles format parts of a paragraph. When you change a style, every paragraph that uses it changes as well, so styles keep a document consistent.

The following button creates a paragraph style named "Note" the first time it is clicked and assigns it to the selected paragraphs:

<input type="button" onclick="applyNoteStyle()" value="Apply Note Style" />

<script>
    function applyNoteStyle() {
        TXTextControl.paragraphStyles.getItem("Note", function (style) {
            if (style) {
                // The document already contains the style
                TXTextControl.selection.setFormattingStyle("Note");
                return;
            }

            TXTextControl.paragraphStyles.add("Note", function (newStyle) {
                if (!newStyle) {
                    return;
                }

                newStyle.setItalic(true, function () {
                    newStyle.paragraphFormat.setLeftIndent(720, function () { // 720 twips = 0.5 inch
                        newStyle.apply(function () {
                            TXTextControl.selection.setFormattingStyle("Note");
                        });
                    });
                });
            });
        }, null);
    }
</script>

The callbacks are nested because each step depends on the previous one: the style must exist before its attributes are set, and it must be applied before it is assigned.

Open the Built-In Dialog Boxes

Instead of building your own controls, you can open the dialog boxes of the editor with showDialog and a value of DialogBoxKind, for example FontDialog, ParagraphFormatDialog, ListFormatDialog, FormattingStylesDialog or TabDialog:

TXTextControl.showDialog(TXTextControl.DialogBoxKind.ParagraphFormatDialog);

The call opens the Paragraph dialog box for the selected paragraphs, the same one the dialog box launcher in the corner of the Paragraph group opens:

Paragraph dialog box of the Document Editor with the tabs Formatting and Indents and Frame and Page Breaks, showing alignment, structure level, line spacing, indentation and distances

React to Formatting Changes

The editor raises charFormatChanged when the character formatting of the selection or the input position changes, and paragraphFormatChanged when the formatting of the selected paragraphs changes. Use them, for example, to update the state of your own formatting buttons. TXTextControl.inputFormat returns all formatting attributes at the input position and has events for single attributes, such as boldChanged. Events lists all events.

Whether formatting is allowed at all depends on the edit mode and the document permissions: getCanCharacterFormat tells your code whether the selected text can be formatted.

Next Steps