Add Math Equations to PowerPoint Presentations in C#
Overview
In PowerPoint, you can write a math equation or formula and display it in your presentation. Various mathematical symbols are available and can be added to text or equations. The math equations constructor is used to create complex formulas like:
- Math fraction
- Math radical
- Math function
- Limits and log functions
- N-ary operations
- Matrix
- Large operators
- Sin, cos functions
To add a mathematical equation in PowerPoint, the Insert -> Equation menu is used:
This will create a mathematical text in XML that can be displayed in PowerPoint as following:
PowerPoint supports a wide range of mathematical symbols for creating equations. However, generating complex math equations in PowerPoint often doesn’t yield a polished, professional result. As a result, users who frequently create mathematical presentations often turn to third-party solutions for better-looking math formulas.
Using the Aspose.Slides API, you can work with math equations in PowerPoint presentations programmatically in C#. Create new math expressions or edit previously created ones. Partial support is available for exporting mathematical structures as images.
How to Create a Mathematical Equation
Mathematical elements are used to build any mathematical construction, regardless of nesting level. A linear collection of these elements forms a mathematical block, represented by the MathBlock class. The MathBlock class represents a standalone mathematical expression, formula, or equation. MathPortion is used to hold mathematical text (distinct from the regular Portion class), while MathParagraph allows you to manipulate a set of MathBlock objects. These classes are essential for working with PowerPoint math equations via the Aspose.Slides API.
Let’s see how we can create the following mathematical equation using the Aspose.Slides API:
To add a mathematical expression to the slide, first add a shape that will contain the mathematical text:
using (var presentation = new Presentation())
{
var mathShape = presentation.Slides[0].Shapes.AddMathShape(0, 0, 720, 150);
}
After creating the shape, it already contains one paragraph with a mathematical portion by default. The MathPortion class represents a portion that contains mathematical text. To access the mathematical content inside a MathPortion, refer to the MathParagraph variable:
var mathParagraph = (mathShape.TextFrame.Paragraphs[0].Portions[0] as MathPortion).MathParagraph;
The MathParagraph class lets you read, add, edit, and delete math blocks (MathBlock), which consist of a combination of mathematical elements. For example, create a fraction and place it in the presentation:
var fraction = new MathematicalText("x").Divide("y");
mathParagraph.Add(new MathBlock(fraction));
Each mathematical element is represented by a class that implements the IMathElement interface. This interface provides numerous methods to easily create mathematical expressions, enabling you to construct fairly complex equations with just a single line of code. For example, the Pythagorean theorem would look like this:
var mathBlock = new MathematicalText("c")
.SetSuperscript("2")
.Join("=")
.Join(new MathematicalText("a").SetSuperscript("2"))
.Join("+")
.Join(new MathematicalText("b").SetSuperscript("2"));
Operations of the IMathElement interface are implemented in every type of element, including the MathBlock class.
Below is the full source code sample:
using (var presentation = new Presentation())
{
var mathShape = presentation.Slides[0].Shapes.AddMathShape(0, 0, 720, 150);
var mathParagraph = (mathShape.TextFrame.Paragraphs[0].Portions[0] as MathPortion).MathParagraph;
var fraction = new MathematicalText("x").Divide("y");
mathParagraph.Add(new MathBlock(fraction));
var mathBlock = new MathematicalText("c")
.SetSuperscript("2")
.Join("=")
.Join(new MathematicalText("a").SetSuperscript("2"))
.Join("+")
.Join(new MathematicalText("b").SetSuperscript("2"));
mathParagraph.Add(mathBlock);
presentation.Save("math.pptx", SaveFormat.Pptx);
}
Mathematical Element Types
Mathematical expressions are composed of sequences of mathematical elements. A mathematical block represents such a sequence, and the arguments of these elements form a nested, tree-like structure.
There are many types of mathematical elements that can be used to construct a mathematical block. Each of these elements can be aggregated within another, forming a tree-like structure. The simplest type of element is one that does not contain any other mathematical text elements.
Each type of math element implements the IMathElement interface, allowing you to use a common set of math operations on different types of math elements.
MathematicalText class
The MathematicalText class represents a mathematical text—the underlying element of all mathematical constructions. Mathematical text may represent operands and operators, variables, or any other linear text.
Example: 𝑎=𝑏+𝑐
MathFraction class
The MathFraction class specifies a fraction object consisting of a numerator and denominator separated by a fraction bar. The fraction bar can be horizontal or diagonal, depending on the fraction properties. The fraction object is also used to represent the stack function, which places one element above another without a fraction bar.
Example:
MathRadical class
The MathRadical class specifies the radical function (mathematical root), consisting of a base and an optional degree.
Example:
MathFunction class
The MathFunction class specifies a function of an argument. It contains properties such as Name, which represents the function name, and Base, which represents the function argument.
Example:
MathNaryOperator class
The MathNaryOperator class specifies an N-ary mathematical object, such as a Summation or Integral. It consists of an operator, a base (or operand), and optional upper and lower limits. Examples of N-ary operators are Summation, Union, Intersection, and Integral. for a couple of seconds The MathNaryOperator class specifies an N-ary mathematical object, such as Summation and Integral. It consists of an operator, a base (or operand), and optional upper and lower limits. Examples of N-ary operators include Summation, Union, Intersection, and Integral.
This class does not include simple operators such as addition, subtraction, and so on. They are represented by a single text MathematicalText.
Example:
MathLimit class
The MathLimit class creates the upper or lower limit. It specifies the limit object, consisting of text on the baseline and reduced-size text immediately above or below it. This element does not include the word “lim”, but allows you to place text at the top or bottom of the expression. So, the expression
is created using a combination of MathFunction and MathLimit elements this way:
var funcName = new MathLimit(new MathematicalText("lim"), new MathematicalText("𝑥→∞"));
var mathFunc = new MathFunction(funcName, new MathematicalText("𝑥"));
MathSubscriptElement, MathSuperscriptElement, MathRightSubSuperscriptElement, MathLeftSubSuperscriptElement classes
- MathSubscriptElement
- MathSuperscriptElement
- MathRightSubSuperscriptElement
- MathLeftSubSuperscriptElement
These classes specify a lower index or an upper index. You can set both subscript and superscript simultaneously on the left or right side of an argument, but a single subscript or superscript is supported only on the right side. The MathSubscriptElement can also be used to set the mathematical degree of a number.
Example:
MathMatrix class
The MathMatrix class specifies the Matrix object, which consists of child elements arranged in one or more rows and columns. It is important to note that matrices do not have built-in delimiters. To enclose the matrix in brackets, use the delimiter object IMathDelimiter. Null arguments can be used to create gaps in matrices.
Example:
MathArray class
The MathArray class specifies a vertical array of equations or any mathematical objects.
Example:
Formatting Mathematical Elements
- MathBorderBox class: Draws a rectangular or alternative border around the IMathElement.
Example:
-
MathBox class: Specifies the logical boxing (packaging) of a mathematical element. A boxed object can serve as an operator emulator—with or without an alignment point—function as a line breakpoint, or be grouped to prevent line breaks within. For example, the “==” operator should be boxed to prevent line breaks.
-
MathDelimiter class: Specifies the delimiter object, which consists of opening and closing characters (such as parentheses, braces, brackets, or vertical bars) and one or more mathematical elements inside, separated by a specified character. Examples include: (𝑥2); [𝑥2|𝑦2].
Example:
- MathAccent class: Specifies the accent function, which consists of a base and a combining diacritical mark.
Example: 𝑎́.
- MathBar class: Specifies the bar function, which consists of a base argument and an overbar or underbar.
Example:
- MathGroupingCharacter class: Specifies a grouping symbol placed above or below an expression, typically to highlight the relationships between elements.
Example:
Mathematical Operations
Each mathematical element and each mathematical expression (via MathBlock) implements the IMathElement interface. This allows you to perform operations on the existing structure and form more complex mathematical expressions. All operations have two sets of parameters: either IMathElement or string arguments. Instances of the MathematicalText class are implicitly created from specified strings when string arguments are used. Math operations available in Aspose.Slides are listed below.
Join method
These methods join a mathematical element and forms a mathematical block. For example:
IMathElement element1 = new MathematicalText("x");
IMathElement element2 = new MathematicalText("y");
IMathBlock block = element1.Join(element2);
Divide method
- Divide(String)
- Divide(IMathElement)
- Divide(String, MathFractionTypes)
- Divide(IMathElement, MathFractionTypes)
These methods create a fraction of the specified type with a numerator and specified denominator. For example:
IMathElement numerator = new MathematicalText("x");
IMathFraction fraction = numerator.Divide("y", MathFractionTypes.Linear);
Enclose method
These methods enclose the element in specified characters, such as parentheses or other framing characters. For example:
IMathDelimiter delimiter = new MathematicalText("x"). Enclose('[', ']');
IMathDelimiter delimiter2 = new MathematicalText("elem1").Join("elem2").Enclose();
Function method
These methods take a function of an argument using the current object as the function name. For example:
IMathFunction func = new MathematicalText("sin").Function("x");
AsArgumentOfFunction method
- AsArgumentOfFunction(String)
- AsArgumentOfFunction(IMathElement)
- AsArgumentOfFunction(MathFunctionsOfOneArgument)
- AsArgumentOfFunction(MathFunctionsOfTwoArguments, IMathElement)
- AsArgumentOfFunction(MathFunctionsOfTwoArguments, String)
These methods take the specified function using the current instance as the argument. You can:
- specify a string as the function name, for example “cos”;
- select one of the predefined values of the enumerations MathFunctionsOfOneArgument or MathFunctionsOfTwoArguments, for example
MathFunctionsOfOneArgument.ArcSin
; - select the instance of the IMathElement.
For example:
var funcName = new MathLimit(new MathematicalText("lim"), new MathematicalText("𝑛→∞"));
var func1 = new MathematicalText("2x").AsArgumentOfFunction(funcName);
var func2 = new MathematicalText("x").AsArgumentOfFunction("sin");
var func3 = new MathematicalText("x").AsArgumentOfFunction(MathFunctionsOfOneArgument.Sin);
var func4 = new MathematicalText("x").AsArgumentOfFunction(MathFunctionsOfTwoArguments.Log, "3")
SetSubscript, SetSuperscript, SetSubSuperscriptOnTheRight, SetSubSuperscriptOnTheLeft methods
- SetSubscript(String)
- SetSubscript(IMathElement)
- SetSuperscript(String)
- SetSuperscript(IMathElement)
- SetSubSuperscriptOnTheRight(String, String)
- SetSubSuperscriptOnTheRight(IMathElement, IMathElement)
- SetSubSuperscriptOnTheLeft(String, String)
- SetSubSuperscriptOnTheLeft(IMathElement, IMathElement)
These methods set subscript and superscript. You can set both simultaneously on either the left or right side of the argument; however, a single subscript or superscript is supported only on the right side. The Superscript can also be used to set the mathematical degree of a number.
Example:
var script = new MathematicalText("y").SetSubSuperscriptOnTheLeft("2x", "3z");
Radical method
These methods specify the mathematical root of the given degree based on the specified argument.
Example:
var radical = new MathematicalText("x").Radical("3");
SetUpperLimit and SetLowerLimit methods
These methods take an upper or lower limit, where “upper” and “lower” indicate the position of the argument relative to the base.
Let’s consider an expression:
Such expressions can be created through a combination of the MathFunction and MathLimit classes, along with operations of the IMathElement interface, as follows:
var mathExpression = MathText.Create("lim").SetLowerLimit("x→∞").Function("x");
Nary and Integral methods
- Nary(MathNaryOperatorTypes, IMathElement, IMathElement)
- Nary(MathNaryOperatorTypes, String, String)
- Integral(MathIntegralTypes)
- Integral(MathIntegralTypes, IMathElement, IMathElement)
- Integral(MathIntegralTypes, String, String)
- Integral(MathIntegralTypes, IMathElement, IMathElement, MathLimitLocations)
- Integral(MathIntegralTypes, String, String, MathLimitLocations)
Both Nary and Integral methods create and return the N-ary operator represented by the INaryOperator type. In the Nary method, the MathNaryOperatorTypes enumeration specifies the type of operator—such as summation or union—excluding integrals. In the Integral method, a specialized operation for integrals is provided, using the MathIntegralTypes enumeration.
Example:
IMathBlock baseArg = new MathematicalText("x").Join(new MathematicalText("dx").ToBox());
IMathNaryOperator integral = baseArg.Integral(MathIntegralTypes.Simple, "0", "1");
ToMathArray method
ToMathArray puts elements into a vertical array. If this operation is called on a MathBlock instance, all its child elements will be placed in the returned array.
Example:
var arrayFunction = new MathematicalText("x").Join("y").ToMathArray();
Formatting operations: Accent, Overbar, Underbar, Group, ToBorderBox, ToBox
- Accent method sets an accent mark (a character on the top of the element).
- Overbar and Underbar methods set a bar on the top or bottom.
- Group method places in a group using a grouping character such as a bottom curly bracket or another.
- ToBorderBox method places in a border-box.
- ToBox method places in a non-visual box (logical grouping).
Examples:
var accent = new MathematicalText("x").Accent('\u0303');
var bar = new MathematicalText("x").Overbar();
var groupChr = new MathematicalText("x").Join("y").Join("z").Group('\u23E1', MathTopBotPositions.Bottom, MathTopBotPositions.Top);
var borderBox = new MathematicalText("x+y+z").ToBorderBox();
var boxedOperator = new MathematicalText(":=").ToBox();
FAQs
How can I add a mathematical equation to a PowerPoint slide?
To add a mathematical equation, you need to create a MathShape
object, which automatically contains a mathematical portion. Then, you retrieve the MathParagraph
from the MathPortion
and add MathBlock
objects to it.
Is it possible to create complex nested mathematical expressions?
Yes, Aspose.Slides allows you to create complex mathematical expressions by nesting MathBlocks. Each mathematical element implements the IMathElement
interface, which allows you to apply operations (Join, Divide, Enclose, etc.) to combine elements into more complex structures.
How can I update or modify an existing mathematical equation?
To update an equation, you need to access the existing MathBlocks through the MathParagraph
. Then, by using methods such as Join, Divide, Enclose, and others, you can modify individual elements of the equation. After editing, save the presentation to apply the changes.