Insert Superscript and Subscript in Word Programmatically in C#

Introduction

A subscript or superscript is a number, figure, symbol, or indicator that is smaller than the normal line of type and is set slightly below or above it. Subscripts and superscripts are often used in math equations, chemical formulas, or behind a phrase(such as a book name, an author name, a theory) that you want to explain more at the bottom of your page. This article is talking about how to add Superscript and Subscript in Word via Free Spire.Doc in C#.

As a standalone component, free Spire.Doc enables developers/programmers to perform plenty range of operations on Word file, such as create, modify, convert and print. In the following section, let’s see detailed steps for inserting Superscript and Subscript with code.

Main Steps

Step 1: Initialize a new instance of Spire.Doc.Document class, add a section, and add a paragraph. These lines of code create a Word document and add a blank paragraph on it.

Document doc = new Document();

Section sec = doc.AddSection();

Paragraph para = sec.AddParagraph();

Step 2: Append text to paragraph using AppendText() method. For the text that you want to make it as Superscript or Subscript, just set the value of TextRange.CharacterFormat.SubSuperScript property as SuperScript or SubScript. Following code will set some texts as Superscript.

para.AppendText(“a”);

para.AppendText(“2”).CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;

para.AppendText(“+b”);

para.AppendText(“2”).CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;

para.AppendText(“=”);

para.AppendText(“c”);

para.AppendText(“2”).CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;

Step 3: Just like step 2, here in this step I created subscripted text in a math equation and a chemical formula.

para.AppendBreak(BreakType.LineBreak);

para.AppendText(“a”);

para.AppendText(“n”).CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SubScript;

para.AppendText(“=s”);

para.AppendText(“n”).CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SubScript;

para.AppendText(“-s”);

para.AppendText(“n-1”).CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SubScript;

para.AppendBreak(BreakType.LineBreak);

para.AppendText(“O”);

para.AppendText(“2”).CharacterFormat.SubSuperScript = Spire.Doc.Documents.SubSuperScript.SubScript;

Step 4: Set font size of this text range as 25. And save the file.

foreach (var i in para.Items)

{

    if (i is TextRange)

    {

        (i as TextRange).CharacterFormat.FontSize = 25;

    }

}

doc.SaveToFile(“result.docx”);

Output:

output

Advertisements