Añadir ecuaciones matemáticas a presentaciones de PowerPoint en .NET
Visión general
PowerPoint almacena ecuaciones como Office Math Markup Language (OMML). Con Aspose.Slides para .NET, puedes crear el mismo tipo de contenido matemático mediante código: fracciones, radicales, funciones, límites, operadores n‑arios, matrices, arreglos y bloques de matemáticas con formato.
En PowerPoint, los usuarios normalmente añaden ecuaciones desde Insertar > Ecuación:

El resultado es texto matemático editable en la diapositiva:

Aspose.Slides construye ese texto matemático a través de tres objetos principales:
- Una forma matemática, creada con AddMathShape, que es la forma que contiene la ecuación.
- MathPortion almacena el contenido matemático dentro del marco de texto de la forma.
- MathParagraph contiene uno o más objetos MathBlock.
La mayoría de los ejemplos a continuación usan MathematicalText y los métodos fluidos de IMathElement para mantener el código breve y legible.
Para escenarios de exportación a MathML, consulta Export Math Equations from Presentations in .NET.
Crear una ecuación
Este ejemplo usa AddMathShape para crear una forma matemática y añade el teorema de Pitágoras:

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 120);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var equation = new MathematicalText("c")
.SetSuperscript("2")
.Join("=")
.Join(new MathematicalText("a").SetSuperscript("2"))
.Join("+")
.Join(new MathematicalText("b").SetSuperscript("2"));
mathParagraph.Add(equation);
presentation.Save("pythagorean-theorem.pptx", SaveFormat.Pptx);
Nota
AddMathShape crea una forma que ya contiene un párrafo matemático. Accede a la primera MathPortion, obtén su MathParagraph, y añade bloques o elementos matemáticos a él.Combinar bloques matemáticos
Cuando partes de una ecuación se construyen independientemente como objetos IMathBlock, usa JoinBlock para combinarlos. El ejemplo construye c² = en el bloque izquierdo y a² + b² en el bloque derecho. SetSuperscript crea superíndices matemáticos editables para los tres exponentes.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var shape = slide.Shapes.AddMathShape(20, 20, 600, 100);
var mathParagraph = ((IMathPortion)shape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var leftBlock = new MathBlock();
leftBlock.Add(new MathematicalText("c").SetSuperscript("2"));
leftBlock.Add(new MathematicalText("="));
var rightBlock = new MathBlock();
rightBlock.Add(new MathematicalText("a").SetSuperscript("2"));
rightBlock.Add(new MathematicalText("+"));
rightBlock.Add(new MathematicalText("b").SetSuperscript("2"));
var combinedBlock = leftBlock.JoinBlock(rightBlock);
mathParagraph.Add(combinedBlock);
presentation.Save("equation.pptx", SaveFormat.Pptx);
JoinBlock devuelve el propio leftBlock, que ahora contiene ambas partes en orden, y deja rightBlock vacío. Añade el bloque combinado al IMathParagraph una única vez. Después de volver a abrir equation.pptx, el párrafo contiene un bloque que representa c² = a² + b², con los tres exponentes conservados como superíndices matemáticos.
Llamar a Add como leftBlock.Add(rightBlock) intenta anidar un bloque dentro de otro y lanza InvalidOperationException.
Añadir fracciones
Usa Divide para crear una fracción. Puedes elegir un estilo de fracción con MathFractionTypes.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 100);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var fraction = new MathematicalText("1")
.Divide("x", MathFractionTypes.Skewed);
mathParagraph.Add(new MathBlock(fraction));
presentation.Save("fraction.pptx", SaveFormat.Pptx);
Para una fracción apilada, usa MathFractionTypes.Bar:
using Aspose.Slides.MathText;
var stackedFraction = new MathematicalText("x + 1").Divide("y - 1", MathFractionTypes.Bar);
Añadir radicales
Usa Radical para crear una raíz cuadrada, cúbica u otro índice. El elemento actual se convierte en la base y el argumento en el grado.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 100);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var radical = new MathematicalText("x")
.Radical("n");
mathParagraph.Add(new MathBlock(radical));
presentation.Save("radical.pptx", SaveFormat.Pptx);
Mostrar u ocultar el grado de una raíz cuadrada
Una raíz cuadrada puede mostrar explícitamente el 2 o usar la notación convencional √x. La propiedad HideDegree de IMathRadical controla qué forma aparece. Ambas formas conservan el grado 2 y el radicando x en la ecuación editable.

El ejemplo guarda la misma raíz cuadrada dos veces. En visible-degree.pptx el 2 es visible. En hidden-degree.pptx está oculto.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var radical = new MathematicalText("x").Radical("2");
var shape = slide.Shapes.AddMathShape(20, 20, 200, 100);
var portion = (IMathPortion)shape.TextFrame.Paragraphs[0].Portions[0];
portion.MathParagraph.Add(new MathBlock(radical));
radical.HideDegree = false;
presentation.Save("visible-degree.pptx", SaveFormat.Pptx);
radical.HideDegree = true;
presentation.Save("hidden-degree.pptx", SaveFormat.Pptx);
Añadir funciones y límites
Usa AsArgumentOfFunction o Function para funciones como sin(x), log(x) o nombres de funciones personalizados. Para límites, coloca lim en un MathLimit o usa SetLowerLimit.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 100);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var limit = new MathematicalText("lim")
.SetLowerLimit("x→∞")
.Function("x");
mathParagraph.Add(new MathBlock(limit));
presentation.Save("functions-and-limits.pptx", SaveFormat.Pptx);
Para un nombre de función personalizado, haz que el nombre de la función sea el elemento actual y llama a Function con su argumento:
using Aspose.Slides.MathText;
var customFunction = new MathematicalText("f").Function("x + 1");
Añadir operadores n‑arios e integrales
Usa Nary para sumas, uniones, intersecciones y otros operadores grandes. Usa Integral para integrales. Ambos métodos permiten establecer límites inferior y superior.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 120);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var summationBase = new MathematicalText("x")
.SetSuperscript("k")
.Join(new MathematicalText("a").SetSuperscript("n-k"));
var summation = summationBase.Nary(MathNaryOperatorTypes.Summation, "k=0", "n");
mathParagraph.Add(new MathBlock(summation));
presentation.Save("nary-operators.pptx", SaveFormat.Pptx);
Los operadores n‑arios son para operadores grandes con límites opcionales. Los operadores simples como +, - y = suelen añadirse como MathematicalText y unirse a la expresión.
Para una integral, usa Integral:
using Aspose.Slides.MathText;
var integralBase = new MathematicalText("x").Join(new MathematicalText("dx").ToBox());
var integral = integralBase.Integral(MathIntegralTypes.Simple, "0", "1");
Crear un operador compuesto
Para usar == como un único operador entre dos operandos, llama a ToBox sobre el MathematicalText que contiene ambos signos de igualdad. En el IMathBox resultante, establece OperatorEmulator a true para que el grupo actúe como operador matemático. El valor predeterminado es false.
NoBreak controla los saltos de línea dentro del recuadro. El ejemplo lo establece explícitamente a su valor predeterminado true para mantener los dos signos de igualdad juntos. El resto de la ecuación aún puede ajustarse.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var shape = slide.Shapes.AddMathShape(20, 20, 300, 60);
var portion = (IMathPortion)shape.TextFrame.Paragraphs[0].Portions[0];
IMathBox compoundOperator = new MathematicalText("==").ToBox();
compoundOperator.OperatorEmulator = true;
compoundOperator.NoBreak = true;
var equation = new MathematicalText("a").Join(compoundOperator).Join(new MathematicalText("b"));
portion.MathParagraph.Add(equation);
presentation.Save("compound-operator.pptx", SaveFormat.Pptx);
Añadir matrices
Usa MathMatrix para filas y columnas. Las matrices no incluyen corchetes por defecto, así que envuelve la matriz cuando necesites paréntesis, corchetes o llaves.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 120);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var matrix = new MathMatrix(2, 3);
matrix[0, 0] = new MathematicalText("1");
matrix[0, 1] = new MathematicalText("x");
matrix[1, 0] = new MathematicalText("x");
matrix[1, 1] = new MathematicalText("2");
matrix[1, 2] = new MathematicalText("y");
mathParagraph.Add(new MathBlock(matrix));
presentation.Save("matrix.pptx", SaveFormat.Pptx);
Mostrar u ocultar marcadores de posición en celdas vacías de la matriz
Por defecto, IMathMatrix.HidePlaceholders es false. PowerPoint muestra un cuadro punteado en cada celda vacía mientras editas la diapositiva. Establece la propiedad a true para ocultar esos cuadros.
El ejemplo siguiente coloca dos matrices 2 × 2 una al lado de la otra. Cada una tiene a y b en la diagonal. Las otras dos celdas quedan null.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
foreach (bool hide in new[] { false, true })
{
IMathMatrix matrix = new MathMatrix(2, 2);
matrix[0, 0] = new MathematicalText("a");
matrix[1, 1] = new MathematicalText("b");
matrix.HidePlaceholders = hide;
var shape = slide.Shapes.AddMathShape(hide ? 360 : 80, 150, 220, 120);
var portion = (IMathPortion)shape.TextFrame.Paragraphs[0].Portions[0];
portion.MathParagraph.Add(new MathBlock(matrix));
}
presentation.Save("matrix-placeholders.pptx", SaveFormat.Pptx);
Abre matrix-placeholders.pptx en la vista Normal de PowerPoint. Haz clic dentro de cualquiera de las ecuaciones para editarlas, luego haz clic en un área en blanco de la diapositiva para comparar ambas matrices.
HidePlaceholders = false |
HidePlaceholders = true |
|---|---|
![]() |
![]() |
Ocultar los marcadores de posición mantiene cada fila y columna intactas. Ambas matrices siguen siendo 2 × 2, y las celdas vacías siguen siendo null sin adquirir un valor cero. Los cuadros punteados son guías de edición en PowerPoint.
Editar una matriz existente
Supongamos que una lección de álgebra lineal comienza con la matriz de coeficientes en matrix.pptx, guardada por el ejemplo anterior. Para el ejercicio siguiente, conserva la primera ecuación, sustituye la segunda por dos ecuaciones nuevas y revisa el conjunto de variables. Abre la matriz existente mediante IMathMatrix para conservar los coeficientes que aún son válidos.

Los índices de filas y columnas comienzan en cero y se refieren a la matriz tal como está en cada llamada. Insertar una fila antes del índice 1 desplaza la fila original segunda al índice 2. Insertar después del índice 2 agrega una fila al final. Eliminar la fila 2 elimina la ecuación original segunda y desplaza la fila añadida una posición arriba. Las columnas se desplazan de la misma manera.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation("matrix.pptx");
var shape = (IAutoShape)presentation.Slides[0].Shapes[0];
var portion = (IMathPortion)shape.TextFrame.Paragraphs[0].Portions[0];
var matrix = (IMathMatrix)portion.MathParagraph[0][0];
matrix.InsertRowBefore(1);
matrix.InsertRowAfter(2);
matrix.DeleteRow(2);
matrix.InsertColumnBefore(1);
matrix.InsertColumnAfter(3);
matrix.DeleteColumn(3);
// Las nuevas celdas son inicialmente nulas. Establece primero los coeficientes distintos de cero.
matrix[1, 0] = new MathematicalText("12");
matrix[1, 1] = new MathematicalText("1");
matrix[2, 2] = new MathematicalText("10");
matrix[2, 3] = new MathematicalText("1");
for (var row = 0; row < matrix.RowCount; row++)
{
for (var column = 0; column < matrix.ColumnCount; column++)
{
matrix[row, column] ??= new MathematicalText("0");
}
}
matrix.SetColumnAlignment(0, MathHorizontalAlignment.Left);
matrix.SetColumnsAlignment(1, 3, MathHorizontalAlignment.Right);
presentation.Save("updated-matrix.pptx", SaveFormat.Pptx);
SetColumnAlignment alinea la primera columna a la izquierda. SetColumnsAlignment alinea tres columnas consecutivas a la derecha, comenzando en el índice 1. En updated-matrix.pptx, la matriz tiene tres ecuaciones y cuatro variables. Los coeficientes originales de la primera fila 1 y x aparecen ahora en la primera y tercera columnas.

Establecer espaciado de filas y columnas de la matriz
El ejemplo crea una matriz 2 × 2 de fracciones con un ancho mínimo de columna de 48 puntos, una separación de columna de 12 puntos y una separación de fila de 1,5 líneas.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var shape = slide.Shapes.AddMathShape(20, 40, 300, 180);
var portion = (IMathPortion)shape.TextFrame.Paragraphs[0].Portions[0];
var matrix = new MathMatrix(2, 2);
matrix[0, 0] = new MathematicalText("1").Divide("2");
matrix[0, 1] = new MathematicalText("1").Divide("3");
matrix[1, 0] = new MathematicalText("2").Divide("3");
matrix[1, 1] = new MathematicalText("3").Divide("4");
matrix.MinColumnWidth = 960;
matrix.ColumnGapRule = MathSpacingRules.Exactly;
matrix.ColumnGap = 240;
matrix.RowGapRule = MathSpacingRules.Multiple;
matrix.RowGap = 3;
portion.MathParagraph.Add(new MathBlock(matrix));
presentation.Save("matrix-spacing.pptx", SaveFormat.Pptx);
MinColumnWidth define el ancho mínimo de cada columna en twips (20 twips = 1 punto). ColumnGap añade espacio entre columnas adyacentes. Ambos contribuyen a la distancia desde el inicio de una columna hasta el inicio de la siguiente.
ColumnGapRule y RowGapRule seleccionan el valor de MathSpacingRules para cada dirección. Con Exactly, ambos valores de espacio se miden en twips. Con Multiple, cada unidad de ColumnGap representa 0,5 em y cada unidad de RowGap representa media línea. Las demás reglas de espaciado de columnas ignoran ColumnGap.
Estos ajustes se aplican dentro de la matriz. El espaciado de párrafo controla el diseño del texto circundante. Para filas dentro de un arreglo de ecuaciones, consulta Configure Row Spacing.
Añadir arreglos de ecuaciones
Usa ToMathArray cuando necesites ecuaciones alineadas o una pila vertical de expresiones.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 140);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var equationArray = new MathematicalText("x")
.Join("y")
.ToMathArray();
mathParagraph.Add(new MathBlock(equationArray));
presentation.Save("equation-array.pptx", SaveFormat.Pptx);
Alinear un arreglo con los elementos circundantes
IMathArray.BaseJustification controla la alineación vertical de un arreglo respecto a los elementos matemáticos que tiene a su lado. El ejemplo a continuación compara la alineación con la primera fila, el centro del arreglo y la última fila.
El siguiente ejemplo crea tres arreglos idénticos, cada uno con tres filas y los elementos vecinos A= y =B. Todo el texto matemático usa Cambria Math a 24 puntos. Sólo cambia la alineación del arreglo.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
presentation.SlideSize.SetSize(780, 200, SlideSizeScaleType.DoNotScale);
var slide = presentation.Slides[0];
var alignments = new[] { MathVerticalAlignment.Top, MathVerticalAlignment.Center, MathVerticalAlignment.Bottom };
for (int i = 0; i < alignments.Length; i++)
{
var label = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 20 + i * 260, 10, 240, 30);
label.FillFormat.FillType = FillType.NoFill;
label.LineFormat.FillFormat.FillType = FillType.NoFill;
label.TextFrame.Text = alignments[i].ToString();
var labelFormat = label.TextFrame.Paragraphs[0].Portions[0].PortionFormat;
labelFormat.FontHeight = 16;
labelFormat.FillFormat.FillType = FillType.Solid;
labelFormat.FillFormat.SolidFillColor.Color = System.Drawing.Color.Black;
var mathShape = slide.Shapes.AddMathShape(20 + i * 260, 60, 240, 130);
mathShape.TextFrame.TextFrameFormat.AnchoringType = TextAnchorType.Top;
var mathParagraph = ((IMathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
mathParagraph.Justification = MathJustification.LeftJustified;
var rows = new IMathElement[] { CreateText("x+y=3"), CreateText("x-y=1"), CreateText("x=2") };
var equationArray = new MathArray(rows);
equationArray.BaseJustification = alignments[i];
var equation = new MathBlock(CreateText("A=")).Join(equationArray).Join(CreateText("=B"));
mathParagraph.Add(equation);
}
presentation.Save("equation-array-alignment.pptx", SaveFormat.Pptx);
MathematicalText CreateText(string value)
{
var text = new MathematicalText(value);
text.Format.FontHeight = 24;
text.Format.LatinFont = new FontData("Cambria Math");
return text;
}
La comparación siguiente muestra la presentación guardada en PowerPoint. Observa la posición de A= y =B junto a cada arreglo.

Configurar espaciado de filas
RowSpacingRule elige la regla de espaciado para filas dentro del arreglo. RowSpacing proporciona un valor numérico para una regla explícita y se ignora cuando se usan reglas predefinidas.
Para espaciado exacto, el valor se mide en puntos. Para espaciado proporcional, se mide en medias líneas: el valor 3 en el ejemplo equivale a 1,5 líneas. Establece ambas propiedades cuando especificas un valor explícito; cambiar sólo el valor numérico no selecciona una regla de espaciado.
El ejemplo a continuación guarda cinco presentaciones con las mismas ecuaciones, alineación y configuración de fuente. Las tres primeras usan preajustes; las dos últimas muestran valores explícitos.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
var settings = new (MathRowSpacingRule Rule, uint Spacing)[]
{
(MathRowSpacingRule.SingleLineGap, 0),
(MathRowSpacingRule.OneAndAHalfLineGap, 0),
(MathRowSpacingRule.TwoLineGap, 0),
(MathRowSpacingRule.Exactly, 20),
(MathRowSpacingRule.Multiple, 3)
};
foreach (var setting in settings)
{
var fileName = $"equation-array-{setting.Rule}.pptx";
using (var presentation = new Presentation())
{
var mathShape = presentation.Slides[0].Shapes.AddMathShape(20, 20, 600, 300);
var paragraph = mathShape.TextFrame.Paragraphs[0];
paragraph.ParagraphFormat.SpaceBefore = 0;
paragraph.ParagraphFormat.SpaceAfter = 0;
var mathParagraph = ((IMathPortion)paragraph.Portions[0]).MathParagraph;
mathParagraph.Justification = MathJustification.LeftJustified;
var rows = new IMathElement[] { CreateText("x+y=3"), CreateText("x-y=1"), CreateText("x=2") };
var equationArray = new MathArray(rows);
equationArray.BaseJustification = MathVerticalAlignment.Center;
equationArray.RowSpacingRule = setting.Rule;
equationArray.RowSpacing = setting.Spacing;
var equation = new MathBlock(CreateText("A=")).Join(equationArray).Join(CreateText("=B"));
mathParagraph.Add(equation);
presentation.Save(fileName, SaveFormat.Pptx);
}
}
MathematicalText CreateText(string value)
{
var text = new MathematicalText(value);
text.Format.FontHeight = 24;
text.Format.LatinFont = new FontData("Cambria Math");
return text;
}
El espaciado de filas del arreglo es independiente del espaciado de párrafo. SpaceBefore y SpaceAfter añaden espacio alrededor del párrafo contenedor, no entre filas del arreglo. Asimismo, IMathParagraph.Justification posiciona todo el párrafo matemático horizontalmente; no sustituye la configuración de alineación vertical del arreglo.
Distribuir columnas de ecuaciones horizontalmente
Usa MaximumDistribution para expandir un arreglo de ecuaciones al ancho disponible en su contenedor, como un marco de texto. Usa ObjectDistribution para repartir las columnas de la ecuación hasta los bordes del propio arreglo. Para alineación vertical respecto al texto circundante, usa BaseJustification. Para espaciado vertical entre filas, usa RowSpacingRule y RowSpacing.
El ejemplo coloca las mismas tres filas en cuatro marcos del mismo tamaño. En x&=1&y&=2, el primer y tercer & alinean los signos de igualdad dentro de sus respectivas columnas. El & del medio separa las columnas para que PowerPoint inserte espacio entre ellas. Los cuatro arreglos usan la misma talla de fuente, espaciado de filas y formato de párrafo.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
presentation.SlideSize.SetSize(720, 440, SlideSizeScaleType.DoNotScale);
var shapes = presentation.Slides[0].Shapes;
var settings = new (string Label, bool Maximum, bool Object)[] {
("Both off", false, false),
("Maximum only", true, false),
("Object only", false, true),
("Both on", true, true)
};
int y = 5;
foreach (var setting in settings)
{
var label = shapes.AddAutoShape(ShapeType.Rectangle, 5, y, 145, 104);
label.TextFrame.Text = setting.Label;
label.TextFrame.Paragraphs[0].Portions[0].PortionFormat.FontHeight = 17;
var frame = shapes.AddMathShape(155, y, 550, 104);
frame.TextFrame.TextFrameFormat.AutofitType = TextAutofitType.None;
var portion = (IMathPortion)frame.TextFrame.Paragraphs[0].Portions[0];
portion.MathParagraph.Justification = MathJustification.LeftJustified;
var rows = new[] { Row("x&=1&y&=2"), Row("a+b+c&=12&z&=u+v"), Row("k&=0&t&=3") };
var array = new MathArray(rows);
array.MaximumDistribution = setting.Maximum;
array.ObjectDistribution = setting.Object;
portion.MathParagraph.Add(new MathBlock(array));
y += 108;
}
presentation.Save("equation-array-distribution.pptx", SaveFormat.Pptx);
MathematicalText Row(string expression)
{
var text = new MathematicalText(expression);
text.Format.FontHeight = 20;
return text;
}
En PowerPoint, Ambos desactivados y Sólo objeto se ven iguales porque el arreglo compacto no tiene ancho extra que distribuir. Con Sólo máximo, PowerPoint deja espacio a ambos lados del contenido del arreglo y entre columnas. Con Ambos activados, las columnas exteriores alcanzan los bordes del ancho disponible y el espacio extra queda entre ellas.

Añadir funciones trigonométricas
Usa AsArgumentOfFunction cuando el argumento sea el elemento actual y el nombre de la función sea conocido.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 100);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var cosine = new MathematicalText("2x")
.AsArgumentOfFunction(MathFunctionsOfOneArgument.Cos);
mathParagraph.Add(new MathBlock(cosine));
presentation.Save("trigonometric-function.pptx", SaveFormat.Pptx);
Añadir subíndices y superíndices
Usa los asistentes de subíndice y superíndice para índices y potencias. Cuando los índices deben aparecer en el lado izquierdo de la base, usa SetSubSuperscriptOnTheLeft.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 100);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var scripts = new MathematicalText("Y")
.SetSubSuperscriptOnTheLeft("1", "n");
mathParagraph.Add(new MathBlock(scripts));
presentation.Save("subscript-superscript.pptx", SaveFormat.Pptx);
Alinear subíndices y superíndices a la derecha
Cuando ambos scripts pertenecen a la misma base, usa MathRightSubSuperscriptElement. Su propiedad AlignScripts controla sus posiciones horizontales: false (valor predeterminado) hace que sigan el contorno de la base, mientras que true alinea los scripts horizontalmente entre sí.
Este ejemplo coloca dos copias de la misma expresión editable una al lado de la otra. Ambas usan la letra itálica matemática f (U+1D453), un subíndice 1, un superíndice 2 y Cambria Math a 72 puntos. La base inclinada hace visible la diferencia en PowerPoint. Instala Cambria Math antes de ejecutar el ejemplo.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
presentation.SlideSize.SetSize(900, 250, SlideSizeScaleType.DoNotScale);
var slide = presentation.Slides[0];
var format = new PortionFormat
{
FontHeight = 72,
LatinFont = new FontData("Cambria Math")
};
for (var i = 0; i < 2; i++)
{
var left = 40 + i * 440;
var shape = slide.Shapes.AddMathShape(left, 75, 380, 150);
var baseText = new MathematicalText("\U0001D453", format);
var subscript = new MathematicalText("1", format);
var superscript = new MathematicalText("2", format);
var scripts = new MathRightSubSuperscriptElement(baseText, subscript, superscript);
scripts.AlignScripts = i == 1;
var portion = (MathPortion)shape.TextFrame.Paragraphs[0].Portions[0];
portion.PortionFormat.FontHeight = format.FontHeight;
portion.PortionFormat.LatinFont = format.LatinFont;
portion.MathParagraph.Add(new MathBlock(scripts));
}
presentation.Save("aligned-scripts.pptx", SaveFormat.Pptx);

A la izquierda, el subíndice comienza más a la izquierda que el superíndice, siguiendo el contorno de la base. A la derecha, ambos scripts se alinean horizontalmente entre sí.
Añadir delimitadores
Usa Enclose para colocar una expresión dentro de delimitadores. También puedes establecer un carácter separador para expresiones delimitadas que contengan varios elementos.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 100);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var delimiter = new MathematicalText("x")
.Join("y")
.Join("z")
.Enclose('<', '>');
delimiter.SeparatorCharacter = '|';
mathParagraph.Add(new MathBlock(delimiter));
presentation.Save("delimiters.pptx", SaveFormat.Pptx);
Tamaño y alineación de delimitadores
Establece GrowToMatchOperandHeight a true para que los paréntesis crezcan alrededor de un operando alto, o a false para mantener su tamaño normal. DelimiterShape acepta uno de los dos valores de MathDelimiterShape. Centered centra los paréntesis en el eje matemático, que pasa por la mitad del signo de igualdad. Match los alinea con el contenido incluido. Ambas configuraciones afectan solo a los delimitadores. La expresión interior permanece igual.
El ejemplo coloca una fracción en el exponente de x de modo que la expresión se extienda más arriba de la línea base que abajo. Las cuatro ecuaciones usan los mismos paréntesis y la misma configuración de fuente.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
void AddExpression(float left, float top, bool grow, MathDelimiterShape shape)
{
var fraction = new MathematicalText("a + b").Divide("c + d");
var power = new MathematicalText("x").SetSuperscript(fraction);
var delimiter = power.Enclose('(', ')');
delimiter.GrowToMatchOperandHeight = grow;
delimiter.DelimiterShape = shape;
var mathShape = slide.Shapes.AddMathShape(left, top, 300, 100);
var portion = (MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0];
portion.PortionFormat.FontHeight = 32;
var equation = new MathematicalText("y = ").Join(delimiter);
portion.MathParagraph.Add(equation);
}
AddExpression(20, 20, true, MathDelimiterShape.Centered);
AddExpression(350, 20, true, MathDelimiterShape.Match);
AddExpression(20, 140, false, MathDelimiterShape.Centered);
AddExpression(350, 140, false, MathDelimiterShape.Match);
presentation.Save("delimiter-sizing.pptx", SaveFormat.Pptx);
En PowerPoint, compara las filas para ver el efecto del crecimiento. En la fila superior, los paréntesis crecen para rodear el exponente y se ven iguales para ambas formas. En la fila inferior, el crecimiento está desactivado. Los paréntesis más pequeños a la izquierda (Centered) se alinean con el signo de igualdad, mientras que los de la derecha (Match) se sitúan más arriba alrededor de la expresión.

Añadir un recuadro delimitador
Llama a ToBorderBox sobre una fracción para encuadrar toda la expresión. El IMathBorderBox devuelto muestra los cuatro lados por defecto. Usa HideTop, HideBottom, HideLeft y HideRight para eliminar lados individuales.
El ejemplo coloca seis copias de la misma fracción en una diapositiva. Para mostrar cancelación, oculta los cuatro lados y establece StrikethroughBottomLeftToTopRight para una diagonal ascendente (↗) o StrikethroughTopLeftToBottomRight para una diagonal descendente (↘). También puedes usar StrikethroughHorizontal o StrikethroughVertical con cualquier combinación de lados visibles.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
presentation.SlideSize.SetSize(540, 220, SlideSizeScaleType.DoNotScale);
var slide = presentation.Slides[0];
IMathBorderBox AddFraction(float x, float y, bool hideBorder = false)
{
var fraction = new MathematicalText("x+1").Divide("y+2");
var box = fraction.ToBorderBox();
box.HideTop = box.HideBottom = box.HideLeft = box.HideRight = hideBorder;
var shape = slide.Shapes.AddMathShape(x, y, 160, 90);
var portion = (MathPortion)shape.TextFrame.Paragraphs[0].Portions[0];
portion.PortionFormat.FontHeight = 28;
portion.MathParagraph.Add(new MathBlock(box));
return box;
}
AddFraction(10, 10);
var partial = AddFraction(190, 10);
partial.HideTop = true;
partial.HideRight = true;
AddFraction(370, 10, hideBorder: true).StrikethroughBottomLeftToTopRight = true;
AddFraction(10, 120, hideBorder: true).StrikethroughTopLeftToBottomRight = true;
AddFraction(190, 120, hideBorder: true).StrikethroughHorizontal = true;
AddFraction(370, 120).StrikethroughVertical = true;
presentation.Save("border-box.pptx", SaveFormat.Pptx);

En esta fracción, la raya horizontal se superpone a la barra de la fracción. La raya vertical cruza tanto el numerador como el denominador mientras el borde circundante sigue visible. Estas líneas decoran toda la expresión. El tachado de texto ordinario se aplica a los caracteres de una ejecución de texto. Después de volver a abrir la presentación en PowerPoint, aún se pueden editar el numerador y el denominador de forma independiente.
Controlar visibilidad y diseño con elementos fantasma
Envuelve una expresión en MathPhantom para controlar su visibilidad y el espacio que aporta a una ecuación de forma independiente. Las propiedades de IMathPhantom controlan lo siguiente:
| Propiedad | Efecto |
|---|---|
| Show | Establecer en false oculta la expresión. Sus dimensiones siguen aportando al diseño a menos que las propiedades correspondientes abajo sean true. |
| ZeroWidth | Tratar el ancho horizontal de la expresión como cero, permitiendo que los elementos vecinos se acerquen más. |
| ZeroAsc | Tratar su ascenso, la altura por encima de la línea base, como cero. Esto puede reducir el espacio reservado sobre los elementos vecinos. |
| ZeroDesc | Tratar su descenso, la profundidad bajo la línea base, como cero. Esto puede acercar una barra de fracción u otro contenido bajo la expresión a sus vecinos. |
La línea base es la línea de referencia sobre la que se sitúan las letras matemáticas ordinarias. Ocultar contenido no elimina sus dimensiones, y tratar una dimensión como cero no borra la expresión. La expresión subyacente sigue disponible a través de Base. Restablece Show a true para volver a mostrarla; la configuración de dimensiones permanece sin cambios.
El ejemplo siguiente crea cinco variantes una al lado de la otra: una fracción visible, una fracción oculta que reserva espacio y tres fracciones ocultas con una dimensión tratada como cero. Cada variante usa la misma expresión circundante y Cambria Math a 24 puntos. Todas las formas de ecuación comparten la misma posición superior, marcada por la guía gris. Colocar el fantasma en el numerador de una fracción exterior facilita la visualización de los cambios de diseño vertical.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
presentation.SlideSize.SetSize(1000, 180, SlideSizeScaleType.DoNotScale);
var slide = presentation.Slides[0];
var labels = new[] { "Visible", "Hidden: reserves space", "Hidden: ZeroWidth", "Hidden: ZeroAsc", "Hidden: ZeroDesc" };
var guide = slide.Shapes.AddAutoShape(ShapeType.Line, 10, 60, 980, 0);
guide.LineFormat.FillFormat.FillType = FillType.Solid;
guide.LineFormat.FillFormat.SolidFillColor.Color = System.Drawing.Color.LightGray;
for (var i = 0; i < labels.Length; i++)
{
var left = 10 + i * 200;
var label = slide.Shapes.AddAutoShape(ShapeType.Rectangle, left, 10, 190, 30);
label.FillFormat.FillType = FillType.NoFill;
label.LineFormat.FillFormat.FillType = FillType.NoFill;
label.TextFrame.Text = labels[i];
var labelFormat = label.TextFrame.Paragraphs[0].Portions[0].PortionFormat;
labelFormat.FontHeight = 14;
labelFormat.FillFormat.FillType = FillType.Solid;
labelFormat.FillFormat.SolidFillColor.Color = System.Drawing.Color.Black;
var fraction = new MathFraction(CreateText("a+b"), CreateText("c+d"));
var phantom = new MathPhantom(fraction);
phantom.Show = i == 0;
phantom.ZeroWidth = i == 2;
phantom.ZeroAsc = i == 3;
phantom.ZeroDesc = i == 4;
var numerator = new MathBlock(CreateText("x+")).Join(phantom).Join(CreateText("+y"));
var equation = new MathFraction(numerator, CreateText("z"));
var shape = slide.Shapes.AddMathShape(left, 60, 190, 100);
shape.TextFrame.TextFrameFormat.AnchoringType = TextAnchorType.Top;
var mathParagraph = ((IMathPortion)shape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
mathParagraph.Add(new MathBlock(equation));
}
presentation.Save("math-phantom.pptx", SaveFormat.Pptx);
MathematicalText CreateText(string value)
{
var text = new MathematicalText(value);
text.Format.FontHeight = 24;
text.Format.LatinFont = new FontData("Cambria Math");
return text;
}

Agrupar términos
Usa Group para colocar un carácter de agrupación encima o debajo de una expresión. Añade un límite para etiquetar los términos agrupados.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 120);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var grouped = new MathematicalText("x + y")
.Group('\u23DF', MathTopBotPositions.Bottom, MathTopBotPositions.Top)
.SetLowerLimit("any text");
mathParagraph.Add(new MathBlock(grouped));
presentation.Save("grouped-terms.pptx", SaveFormat.Pptx);
Dar formato a los elementos matemáticos
Utiliza los asistentes de formato solo donde clarifiquen la fórmula. Por ejemplo, Overbar coloca una barra sobre un elemento matemático.

using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var mathShape = slide.Shapes.AddMathShape(20, 20, 700, 100);
var mathParagraph = ((MathPortion)mathShape.TextFrame.Paragraphs[0].Portions[0]).MathParagraph;
var overbar = new MathematicalText("ABC").Overbar();
mathParagraph.Add(new MathBlock(overbar));
presentation.Save("overbar.pptx", SaveFormat.Pptx);
Usar una fuente de símbolos en una ecuación
Para insertar una flecha Wingdings entre dos operandos, crea un elemento MathematicalText separado para la flecha. Establece su SymbolFont a través de MathematicalText.Format. Así solo la flecha usa la fuente Wingdings y se preserva el formato de ambos operandos.
Elige el código de carácter y la fuente de símbolos conjuntamente. Wingdings muestra U+F0E0 como una flecha hacia la derecha. Otra fuente puede mostrar un glifo diferente en ese punto de código o no tener glifo alguno.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation();
var slide = presentation.Slides[0];
var shape = slide.Shapes.AddMathShape(20, 20, 240, 90);
var mathPortion = (IMathPortion)shape.TextFrame.Paragraphs[0].Portions[0];
var left = new MathematicalText("A");
var arrow = new MathematicalText("\uF0E0");
var right = new MathematicalText("B");
arrow.Format.SymbolFont = new FontData("Wingdings");
var block = new MathBlock();
block.Add(left);
block.Add(arrow);
block.Add(right);
mathPortion.MathParagraph.Add(block);
presentation.Save("symbol-font-arrow.pptx", SaveFormat.Pptx);
PowerPoint muestra la ecuación guardada como se ve a continuación. Los tres elementos siguen siendo editables.

LoadOptions.DefaultSymbolFont configura la fuente de símbolos predeterminada al cargar una presentación. Asignar una fuente de símbolos a un elemento individual no incrusta la fuente en la presentación. Wingdings debe estar disponible en el entorno de renderizado.
Dar formato al texto en una ecuación existente
Para dar formato al texto en una ecuación existente, recorre el árbol de elementos de cada bloque matemático. IMathElement.GetChildren devuelve solo los hijos inmediatos, por lo que debes llamarlo recursivamente para alcanzar texto dentro de fracciones, scripts, radicales y otras estructuras anidadas. Comprueba el elemento actual así como sus hijos para incluir el elemento inicial cuando sea MathematicalText.
Este ejemplo asume que una presentación contiene una ecuación como z = xᵢ / ∛y, con una fracción que contiene un subíndice en el numerador y un radical en el denominador. Procesar solo los elementos de nivel superior del bloque perdería el texto dentro de la fracción. El ejemplo encuentra porciones matemáticas en los marcos de texto de diapositivas, accede a sus bloques a través de IMathPortion.MathParagraph, y establece FontHeight a 28 puntos mediante la propiedad Format de cada elemento de texto.
using Aspose.Slides;
using Aspose.Slides.Export;
using Aspose.Slides.MathText;
using var presentation = new Presentation("input.pptx");
foreach (var slide in presentation.Slides)
{
foreach (var shape in slide.Shapes)
{
if (shape is not IAutoShape autoShape || autoShape.TextFrame == null)
continue;
foreach (var paragraph in autoShape.TextFrame.Paragraphs)
{
foreach (var portion in paragraph.Portions)
{
if (portion is IMathPortion mathPortion)
{
foreach (var block in mathPortion.MathParagraph)
FormatMathText(block);
}
}
}
}
}
presentation.Save("formatted-equations.pptx", SaveFormat.Pptx);
void FormatMathText(IMathElement element)
{
if (element is MathematicalText text)
text.Format.FontHeight = 28;
foreach (var child in element.GetChildren())
FormatMathText(child);
}
La presentación guardada contiene el formato de texto actualizado en todos los niveles de cada ecuación procesada, conservando su contenido textual y su estructura matemática.
Referencia rápida
| Tarea | API principal |
|---|---|
| Crear texto matemático | MathematicalText |
| Combinar elementos | IMathElement.Join |
| Crear fracciones | IMathElement.Divide |
| Añadir superíndice o subíndice | SetSuperscript, SetSubscript |
| Añadir funciones | Function, AsArgumentOfFunction |
| Añadir radicales | IMathElement.Radical |
| Añadir límites | SetLowerLimit, SetUpperLimit |
| Añadir scripts del lado izquierdo | SetSubSuperscriptOnTheLeft |
| Añadir sumas e integrales | Nary, Integral |
| Añadir matrices | MathMatrix |
| Añadir arreglos de ecuaciones | ToMathArray |
| Añadir delimitadores | Enclose |
| Añadir barras y bordes | Overbar, ToBorderBox |
| Agrupar términos | Group |
FAQ
¿Puedo editar una ecuación de PowerPoint existente?
Sí. Abre la presentación, localiza la forma que contiene una MathPortion, obtén su MathParagraph, y actualiza los bloques matemáticos en ese párrafo.
¿Se guardan las ecuaciones como matemáticas editables de PowerPoint?
Sí. Cuando guardas en PPTX, Aspose.Slides escribe la ecuación como contenido Office math editable.
¿Puedo exportar ecuaciones a LaTeX?
Sí. Obtén el IMathParagraph de su MathPortion, y llama a IMathParagraph.ToLatex para exportarlo directamente. Para un ejemplo completo, consulta Export Math Equations from Presentations in .NET.

