Añadir ecuaciones matemáticas a presentaciones de PowerPoint en .NET
Visión general
PowerPoint almacena las ecuaciones como Office Math Markup Language (OMML). Con Aspose.Slides para .NET, puede crear el mismo tipo de contenido matemático de forma programática: fracciones, radicales, funciones, límites, operadores N-arios, matrices, arreglos y bloques matemáticos 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 crea ese texto matemático mediante tres objetos principales:
- Una forma matemática, creada con AddMathShape, 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 que el código sea corto y legible.
Para escenarios de exportación a MathML, consulte 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);
Note
AddMathShape crea una forma que ya contiene un párrafo matemático. Acceda al primer MathPortion, obtenga su MathParagraph, y añada bloques o elementos matemáticos a él.Combinar bloques matemáticos
Cuando partes de una ecuación se construyen independientemente como objetos IMathBlock, use 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ñada el bloque combinado al IMathParagraph solo una 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 directamente dentro de otro y lanza InvalidOperationException.
Añadir fracciones
Use Divide para crear una fracción. Puede 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, use MathFractionTypes.Bar:
using Aspose.Slides.MathText;
var stackedFraction = new MathematicalText("x + 1").Divide("y - 1", MathFractionTypes.Bar);
Añadir radicales
Use Radical para crear una raíz cuadrada, cúbica u otra raíz. 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 un 2 explícito 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
Use AsArgumentOfFunction o Function para funciones como sin(x), log(x) o nombres de funciones personalizados. Para límites, coloque lim en un MathLimit o use 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, convierta el nombre de la función en el elemento actual y llame a Function con su argumento:
using Aspose.Slides.MathText;
var customFunction = new MathematicalText("f").Function("x + 1");
Añadir operadores N-arios e integrales
Use Nary para sumas, uniones, intersecciones y otros operadores grandes. Use 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. Operadores simples como +, - y = suelen añadirse como MathematicalText y unirse a la expresión.
Para una integral, use 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 solo operador entre dos operandos, llame a ToBox sobre el MathematicalText que contiene ambos signos de igualdad. En el IMathBox resultante, establezca OperatorEmulator a true para que el grupo actúe como un operador matemático. El valor predeterminado es false.
NoBreak controla los saltos de línea dentro del cuadro. El ejemplo lo establece explícitamente a su valor predeterminado true para mantener juntos los dos signos de igualdad. 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
Use MathMatrix para filas y columnas. Las matrices no incluyen corchetes por defecto, así que envuelva la matriz cuando necesite 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 de matriz vacías
Por defecto, IMathMatrix.HidePlaceholders es false. PowerPoint muestra un cuadro punteado en cada celda vacía mientras edita la diapositiva. Establezca la propiedad a true para ocultar esos cuadros.
El siguiente ejemplo 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);
Abra matrix-placeholders.pptx en la vista Normal de PowerPoint. Haga clic dentro de cualquiera de las ecuaciones para editarla, luego haga clic en un área en blanco de la diapositiva para comparar ambas matrices.
HidePlaceholders = false |
HidePlaceholders = true |
|---|---|
![]() |
![]() |
Ocultar los marcadores de posición mantiene intactas todas las filas y columnas. Ambas matrices siguen siendo 2×2, y las celdas vacías permanecen 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 siguiente ejercicio, mantenga la primera ecuación, reemplace la segunda con dos ecuaciones nuevas y revise el conjunto de variables. Abra la matriz existente mediante IMathMatrix para conservar los coeficientes que siguen siendo aplicables.

Los índices de filas y columnas empiezan en cero y se refieren a la matriz tal como está en cada llamada. Insertar una fila antes del índice 1 desplaza la segunda fila original al índice 2. Insertar después del índice 2 entonces agrega una fila. Eliminar la fila 2 quita la segunda ecuación original 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. Establezca 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 establece el ancho mínimo de cada columna en twips (20 twips = 1 punto). ColumnGap agrega espacio entre columnas adyacentes. Ambos contribuyen a la distancia desde el inicio de una columna al inicio de la siguiente.
ColumnGapRule y RowGapRule seleccionan el valor de MathSpacingRules para cada dirección. Con Exactly, ambos valores de separación 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, consulte Configure Row Spacing.
Añadir arreglos de ecuaciones
Use ToMathArray cuando necesite 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 a su lado. El ejemplo siguiente 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. Solo 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. Observe la posición de A= y =B junto a cada arreglo.

Configurar espaciado de filas
RowSpacingRule selecciona la regla de espaciado para filas dentro del arreglo. RowSpacing aporta un valor numérico para una regla de espaciado explícita y se ignora cuando se usan las reglas predefinidas.
Para espaciado exacto, el valor se mide en puntos. Para espaciado proporcional, se mide en mitades de línea: el valor 3 del ejemplo equivale a 1,5 líneas. Establezca ambas propiedades cuando especifique un valor explícito; cambiar solo 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 valores predefinidos; 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. De forma similar, IMathParagraph.Justification posiciona horizontalmente todo el párrafo matemático; no sustituye la configuración de alineación vertical del arreglo.
Añadir funciones trigonométricas
Use AsArgumentOfFunction cuando el argumento es el elemento actual y se conoce el nombre de la función.

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
Use los asistentes de subíndice y superíndice para índices y potencias. Cuando los índices deben aparecer a la izquierda de la base, use 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 derechos
Cuando ambos scripts pertenecen a la misma base, use MathRightSubSuperscriptElement. Su propiedad AlignScripts controla sus posiciones horizontales: false (valor predeterminado) permite que sigan el contorno de la base, mientras que true alinea horizontalmente los scripts 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 script inferior 1, un script superior 2 y Cambria Math a 72 puntos. La base inclinada hace visible la diferencia en PowerPoint. Instale 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 script inferior empieza más a la izquierda que el superior, siguiendo el contorno de la base. A la derecha, ambos scripts se alinean horizontalmente entre sí.
Añadir delimitadores
Use Enclose para colocar una expresión dentro de delimitadores. También puede establecer un carácter separador para expresiones delimitadoras 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
Establezca 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 dos valores de MathDelimiterShape. Centered centra los paréntesis en el eje matemático, que atraviesa el medio del signo igual. Match los alinea con el contenido encerrado. 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, compare las filas para ver el efecto del crecimiento. En la fila superior, los paréntesis crecen para encerrar el exponente y lucen 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 igual, mientras que los de la derecha (Match) se sitúan más altos alrededor de la expresión.

Añadir un cuadro con borde
Llame a ToBorderBox sobre una fracción para encuadrar toda la expresión. El IMathBorderBox devuelto muestra los cuatro lados por defecto. Use HideTop, HideBottom, HideLeft y HideRight para eliminar lados individuales.
El ejemplo coloca seis copias de la misma fracción en una diapositiva. Para mostrar una cancelación, oculte los cuatro lados y establezca StrikethroughBottomLeftToTopRight para una diagonal ascendente (↗) o StrikethroughTopLeftToBottomRight para una diagonal descendente (↘). También puede 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 normal se aplica a caracteres en una ejecución de texto. Después de volver a abrir la presentación en PowerPoint, aún puede editar el numerador y el denominador de forma independiente.
Controlar la visibilidad y el diseño con elementos fantasma
Envuelva 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:
| Property | Effect |
|---|---|
| Show | Establezca false para ocultar la expresión. Sus dimensiones siguen contribuyendo al diseño a menos que las propiedades correspondientes a continuación sean true. |
| ZeroWidth | Trata el ancho horizontal de la expresión como cero, permitiendo que los elementos vecinos se acerquen más. |
| ZeroAsc | Trata su ascendente, la altura por encima de la línea base, como cero. Esto puede reducir el espacio reservado arriba de los elementos vecinos. |
| ZeroDesc | Trata su descendente, 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. Restablezca Show a true para volver a mostrarla; la configuración de dimensiones permanece sin cambios.
El siguiente ejemplo 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 tienen la misma posición superior, marcada por la guía gris. Colocar el fantasma en el numerador de una fracción externa facilita ver 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
Use Group para colocar un carácter de agrupación sobre o bajo una expresión. Añada 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);
Formato de elementos matemáticos
Use 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, cree un elemento MathematicalText separado para la flecha. Establezca su SymbolFont mediante MathematicalText.Format. Así solo la flecha usa la fuente Wingdings y se conserva el formato de ambos operandos.
Elija el código de carácter y la fuente de símbolos conjuntamente. Wingdings muestra U+F0E0 como una flecha 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 toda una ecuación existente, recorra el árbol de elementos de cada bloque matemático. IMathElement.GetChildren devuelve solo los hijos inmediatos, por lo que debe llamarse recursivamente para alcanzar el texto dentro de fracciones, scripts, radicales y otras estructuras anidadas. Verifique también el elemento actual, además de 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 omitirí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 cada nivel de cada ecuación procesada, conservando su contenido textual y su estructura matemática.
Referencia rápida
| Task | Main API |
|---|---|
| Create math text | MathematicalText |
| Combine elements | IMathElement.Join |
| Create fractions | IMathElement.Divide |
| Add superscript or subscript | SetSuperscript, SetSubscript |
| Add functions | Function, AsArgumentOfFunction |
| Add radicals | IMathElement.Radical |
| Add limits | SetLowerLimit, SetUpperLimit |
| Add left-side scripts | SetSubSuperscriptOnTheLeft |
| Add summations and integrals | Nary, Integral |
| Add matrices | MathMatrix |
| Add equation arrays | ToMathArray |
| Add delimiters | Enclose |
| Add bars and borders | Overbar, ToBorderBox |
| Group terms | Group |
FAQ
¿Puedo editar una ecuación existente de PowerPoint?
Sí. Abra la presentación, encuentre la forma que contiene un MathPortion, obtenga su MathParagraph, y actualice los bloques matemáticos en ese párrafo.
¿Se guardan las ecuaciones como matemáticas editables de PowerPoint?
Sí. Al guardar en PPTX, Aspose.Slides escribe la ecuación como contenido matemático de Office editable.
¿Puedo exportar ecuaciones a LaTeX?
Sí. Obtenga el IMathParagraph de su MathPortion, y llame a IMathParagraph.ToLatex para exportarla directamente. Para un ejemplo completo, consulte Export Math Equations from Presentations in .NET.

