Add Math Equations to PowerPoint Presentations in PHP

Overview

PowerPoint stores equations as Office Math Markup Language (OMML). With Aspose.Slides for PHP via Java, you can create the same kind of math content programmatically: fractions, radicals, functions, limits, N-ary operators, matrices, arrays, and formatted math blocks.

In PowerPoint, users normally add equations from Insert > Equation:

PowerPoint Insert tab with the Equation command selected

The result is editable math text on the slide:

A PowerPoint slide containing an editable math equation

Aspose.Slides builds that math text through three main objects:

Most examples below use MathematicalText and the fluent methods from MathElementBase to keep the code short and readable.

For MathML export scenarios, see Export Math Equations from Presentations in PHP via Java.

Create an Equation

This example uses addMathShape to create a math shape and adds the Pythagorean theorem:

The equation c squared equals a squared plus b squared

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 120);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $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);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Combine Math Blocks

When parts of an equation are built independently as MathBlock objects, use joinBlock to combine them. The example builds c² = in the left block and a² + b² in the right block. setSuperscript creates editable mathematical superscripts for all three powers.

use aspose\slides\MathBlock;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $shape = $slide->getShapes()->addMathShape(20, 20, 600, 100);
    $mathPortion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
    $mathParagraph = $mathPortion->getMathParagraph();

    $leftBlock = new MathBlock();
    $leftBlock->add((new MathematicalText("c"))->setSuperscript("2"));
    $leftBlock->add(new MathematicalText("="));

    $rightBlock = new MathBlock();
    $rightBlock->add((new MathematicalText("a"))->setSuperscript("2"));
    $rightBlock->add(new MathematicalText("+"));
    $rightBlock->add((new MathematicalText("b"))->setSuperscript("2"));

    $combinedBlock = $leftBlock->joinBlock($rightBlock);
    $mathParagraph->add($combinedBlock);

    $presentation->save("equation.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

joinBlock returns $leftBlock itself, now containing both parts in order, and leaves $rightBlock empty. Add the combined block to the MathParagraph only once. After reopening equation.pptx, the paragraph contains one block representing c² = a² + b², with all three powers preserved as mathematical superscripts.

Calling add as $leftBlock->add($rightBlock) instead attempts to nest one block directly inside another and throws InvalidOperationException.

Add Fractions

Use divide to create a fraction. You can choose a fraction style with MathFractionTypes.

A skewed math fraction showing one divided by x

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 100);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $fraction = (new MathematicalText("1"))
        ->divide("x", MathFractionTypes::Skewed);

    $mathParagraph->add(new MathBlock($fraction));

    $presentation->save("fraction.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

For a stacked fraction, use MathFractionTypes::Bar:

$stackedFraction = (new MathematicalText("x + 1"))->divide("y - 1", MathFractionTypes::Bar);

Add Radicals

Use radical to create a square root, cube root, or other root. The current element becomes the base, and the argument becomes the degree.

An n-th root radical expression with x under the radical sign

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 100);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $radical = (new MathematicalText("x"))
        ->radical("n");

    $mathParagraph->add(new MathBlock($radical));

    $presentation->save("radical.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Show or Hide the Degree of a Square Root

A square root can display an explicit 2 or use the conventional √x notation. The setHideDegree method of MathRadical controls which form appears. Both forms retain the degree 2 and the radicand x in the editable equation.

The same square root with the degree visible on the left and hidden on the right

The example saves the same square root twice. In visible-degree.pptx, the 2 is visible. In hidden-degree.pptx, it is hidden.

use aspose\slides\MathBlock;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);
    
    $radical = (new MathematicalText("x"))->radical("2");

    $shape = $slide->getShapes()->addMathShape(20, 20, 200, 100);
    $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
    $portion->getMathParagraph()->add(new MathBlock($radical));

    $radical->setHideDegree(false);
    $presentation->save("visible-degree.pptx", SaveFormat::Pptx);

    $radical->setHideDegree(true);
    $presentation->save("hidden-degree.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

Add Functions and Limits

Use asArgumentOfFunction or function for functions such as sin(x), log(x), or custom function names. For limits, put lim in a MathLimit or use setLowerLimit.

The limit of x as x approaches infinity

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 100);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $limit = (new MathematicalText("lim"))
        ->setLowerLimit("x\u{2192}\u{221E}")
        ->function("x");

    $mathParagraph->add(new MathBlock($limit));

    $presentation->save("functions-and-limits.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

For a custom function name, make the function name the current element and call function with its argument:

$customFunction = (new MathematicalText("f"))->function("x + 1");

Add N-ary Operators and Integrals

Use nary for summations, unions, intersections, and other large operators. Use integral for integrals. Both methods let you set lower and upper limits.

A summation with lower and upper limits

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 120);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $summationBase = (new MathematicalText("x"))
        ->setSuperscript("k")
        ->join((new MathematicalText("a"))->setSuperscript("n-k"));

    $summation = $summationBase->nary(MathNaryOperatorTypes::Summation, "k=0", "n");

    $mathParagraph->add(new MathBlock($summation));

    $presentation->save("nary-operators.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

N-ary operators are for large operators with optional limits. Simple operators such as +, -, and = are usually added as MathematicalText and joined into the expression.

For an integral, use integral:

$integralBase = (new MathematicalText("x"))->join((new MathematicalText("dx"))->toBox());
$integral = $integralBase->integral(MathIntegralTypes::Simple, "0", "1");

Create a Compound Operator

To use == as a single operator between two operands, call toBox on the MathematicalText containing both equals signs. On the resulting MathBox, call setOperatorEmulator with true so the group acts as a mathematical operator. The default is false.

setNoBreak controls line breaks inside the box. The example explicitly sets this option to its default value of true to keep the two equals signs together. The rest of the equation can still wrap.

use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $shape = $slide->getShapes()->addMathShape(20, 20, 300, 60);
    $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);

    $compoundOperator = (new MathematicalText("=="))->toBox();
    $compoundOperator->setOperatorEmulator(true);
    $compoundOperator->setNoBreak(true);

    $equation = (new MathematicalText("a"))->join($compoundOperator)->join(new MathematicalText("b"));
    $portion->getMathParagraph()->add($equation);

    $presentation->save("compound-operator.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

Add Matrices

Use MathMatrix for rows and columns. Matrices do not include brackets by default, so enclose the matrix when you need parentheses, brackets, or braces.

A two-row math matrix with one empty cell

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 120);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $matrix = new MathMatrix(2, 3);
    $matrix->set_Item(0, 0, new MathematicalText("1"));
    $matrix->set_Item(0, 1, new MathematicalText("x"));
    $matrix->set_Item(1, 0, new MathematicalText("x"));
    $matrix->set_Item(1, 1, new MathematicalText("2"));
    $matrix->set_Item(1, 2, new MathematicalText("y"));

    $mathParagraph->add(new MathBlock($matrix));

    $presentation->save("matrix.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Show or Hide Placeholders in Empty Matrix Cells

By default, MathMatrix::getHidePlaceholders returns false. PowerPoint shows a dotted box in each empty cell while you edit the slide. Call setHidePlaceholders with true to hide those boxes.

The following example places two 2×2 matrices side by side. Each has a and b on the diagonal. The other two cells are left null.

use aspose\slides\MathBlock;
use aspose\slides\MathematicalText;
use aspose\slides\MathMatrix;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    foreach ([false, true] as $hide) {
        $matrix = new MathMatrix(2, 2);
        $matrix->set_Item(0, 0, new MathematicalText("a"));
        $matrix->set_Item(1, 1, new MathematicalText("b"));
        $matrix->setHidePlaceholders($hide);

        $shape = $slide->getShapes()->addMathShape($hide ? 360 : 80, 150, 220, 120);
        $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
        $portion->getMathParagraph()->add(new MathBlock($matrix));
    }

    $presentation->save("matrix-placeholders.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

Open matrix-placeholders.pptx in PowerPoint’s Normal view. Click inside either equation to edit it, then click a blank area of the slide to compare both matrices.

setHidePlaceholders(false) setHidePlaceholders(true)
PowerPoint shows dotted boxes in the two empty cells. PowerPoint shows only the diagonal entries, a and b.

Hiding the placeholders keeps every row and column intact. Both matrices remain 2×2, and the empty cells remain null without acquiring a zero value. The dotted boxes are editing guides in PowerPoint.

Edit an Existing Matrix

Suppose a linear algebra lesson starts with the coefficient matrix in matrix.pptx, saved by the preceding example. For the next exercise, keep the first equation, replace the second with two new equations, and revise the set of variables. Open the existing matrix through MathMatrix to keep the coefficients that still apply.

Original two-row coefficient matrix with entries 1, x, and an empty cell in the first row and x, 2, and y in the second

Row and column indices start at zero and refer to the matrix as it stands at each call. Inserting a row before index 1 moves the original second row to index 2. Inserting after index 2 then appends a row. Deleting row 2 removes the original second equation and moves the appended row up one position. Columns shift in the same way.

use aspose\slides\MathematicalText;
use aspose\slides\MathHorizontalAlignment;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation("matrix.pptx");
try {
    $shape = $presentation->getSlides()->get_Item(0)->getShapes()->get_Item(0);
    $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
    $block = $portion->getMathParagraph()->get_Item(0);
    $matrix = $block->get_Item(0);

    $matrix->insertRowBefore(1);
    $matrix->insertRowAfter(2);
    $matrix->deleteRow(2);

    $matrix->insertColumnBefore(1);
    $matrix->insertColumnAfter(3);
    $matrix->deleteColumn(3);

    // New cells are initially null. Set the nonzero coefficients first.
    $matrix->set_Item(1, 0, new MathematicalText("12"));
    $matrix->set_Item(1, 1, new MathematicalText("1"));
    $matrix->set_Item(2, 2, new MathematicalText("10"));
    $matrix->set_Item(2, 3, new MathematicalText("1"));
    $rowCount = java_values($matrix->getRowCount());
    $columnCount = java_values($matrix->getColumnCount());
    for ($row = 0; $row < $rowCount; $row++) {
        for ($column = 0; $column < $columnCount; $column++) {
            $coefficient = $matrix->get_Item($row, $column);
            if (java_is_null($coefficient)) {
                $matrix->set_Item($row, $column, new MathematicalText("0"));
            }
        }
    }

    $matrix->setColumnAlignment(0, MathHorizontalAlignment::Left);
    $matrix->setColumnsAlignment(1, 3, MathHorizontalAlignment::Right);

    $presentation->save("updated-matrix.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

setColumnAlignment aligns the first column to the left. setColumnsAlignment aligns three consecutive columns to the right, starting at index 1. In updated-matrix.pptx, the matrix has three equations and four variables. The original first-row coefficients 1 and x now appear in the first and third columns.

Updated three-row matrix showing the rows 1, 0, x, 0; 12, 1, 0, 0; and 0, 0, 10, 1

Set Matrix Row and Column Spacing

The example creates a 2 × 2 matrix of fractions with a minimum column width of 48 points, a column gap of 12 points, and a row gap of 1.5 lines.

use aspose\slides\MathBlock;
use aspose\slides\MathematicalText;
use aspose\slides\MathMatrix;
use aspose\slides\MathSpacingRules;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $shape = $slide->getShapes()->addMathShape(20, 40, 300, 180);
    $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);

    $matrix = new MathMatrix(2, 2);
    $matrix->set_Item(0, 0, (new MathematicalText("1"))->divide("2"));
    $matrix->set_Item(0, 1, (new MathematicalText("1"))->divide("3"));
    $matrix->set_Item(1, 0, (new MathematicalText("2"))->divide("3"));
    $matrix->set_Item(1, 1, (new MathematicalText("3"))->divide("4"));

    $matrix->setMinColumnWidth(960);
    $matrix->setColumnGapRule(MathSpacingRules::Exactly);
    $matrix->setColumnGap(240);
    $matrix->setRowGapRule(MathSpacingRules::Multiple);
    $matrix->setRowGap(3);

    $portion->getMathParagraph()->add(new MathBlock($matrix));
    
    $presentation->save("matrix-spacing.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

setMinColumnWidth sets the minimum width of each column in twips (20 twips = 1 point). setColumnGap adds space between adjacent columns. Both contribute to the distance from the start of one column to the start of the next.

setColumnGapRule and setRowGapRule select the MathSpacingRules value for each direction. With Exactly, both gap values are measured in twips. With Multiple, each unit passed to setColumnGap represents 0.5 em, and each unit passed to setRowGap represents half a line. The other column spacing rules ignore the value passed to setColumnGap.

These settings apply within the matrix. Paragraph spacing controls the surrounding text layout. For rows within an equation array, see Configure Row Spacing.

Add Equation Arrays

Use toMathArray when you need aligned equations or a vertical stack of expressions.

A vertical math array with x above y

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 140);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $equationArray = (new MathematicalText("x"))
        ->join("y")
        ->toMathArray();

    $mathParagraph->add(new MathBlock($equationArray));

    $presentation->save("equation-array.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Align an Array with Surrounding Elements

setBaseJustification controls the vertical alignment of an array relative to the mathematical elements beside it. The example below compares alignment with the first row, the center of the array, and the last row.

The following example creates three identical arrays, each with three rows and the neighboring elements A= and =B. All mathematical text uses Cambria Math at 24 points. Only the array alignment changes.

use aspose\slides\FillType;
use aspose\slides\FontData;
use aspose\slides\MathArray;
use aspose\slides\MathBlock;
use aspose\slides\MathJustification;
use aspose\slides\MathVerticalAlignment;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
use aspose\slides\SlideSizeScaleType;
use aspose\slides\TextAnchorType;

$createText = static function (string $value) {
    $text = new MathematicalText($value);
    $text->getFormat()->setFontHeight(24);
    $text->getFormat()->setLatinFont(new FontData("Cambria Math"));
    return $text;
};

$alignments = ["Top" => MathVerticalAlignment::Top, "Center" => MathVerticalAlignment::Center, "Bottom" => MathVerticalAlignment::Bottom];
$presentation = new Presentation();
try {
    $presentation->getSlideSize()->setSize(780, 200, SlideSizeScaleType::DoNotScale);
    $slide = $presentation->getSlides()->get_Item(0);
    $x = 20;
    foreach ($alignments as $name => $alignment) {
        $label = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, $x, 10, 240, 30);
        $label->getFillFormat()->setFillType(FillType::NoFill);
        $label->getLineFormat()->getFillFormat()->setFillType(FillType::NoFill);
        $label->getTextFrame()->setText($name);
        $labelFormat = $label->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0)->getPortionFormat();
        $labelFormat->setFontHeight(16);
        $labelFormat->getFillFormat()->setFillType(FillType::Solid);
        $labelFormat->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);

        $mathShape = $slide->getShapes()->addMathShape($x, 60, 240, 130);
        $mathShape->getTextFrame()->getTextFrameFormat()->setAnchoringType(TextAnchorType::Top);
        $paragraph = $mathShape->getTextFrame()->getParagraphs()->get_Item(0);
        $mathParagraph = $paragraph->getPortions()->get_Item(0)->getMathParagraph();
        $mathParagraph->setJustification(MathJustification::LeftJustified);

        $firstRow = $createText("x+y=3");
        $equationArray = new MathArray($firstRow);
        foreach (["x-y=1", "x=2"] as $value) {
            $row = $createText($value);
            $equationArray->getArguments()->add($row);
        }
        $equationArray->setBaseJustification($alignment);
        $leftText = $createText("A=");
        $rightText = $createText("=B");
        $equation = (new MathBlock($leftText))->join($equationArray)->join($rightText);
        $mathParagraph->add($equation);
        $x += 260;
    }
    $presentation->save("equation-array-alignment.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

The following comparison shows the saved presentation in PowerPoint. Notice the position of A= and =B beside each array.

Equation arrays in PowerPoint with Top, Center, and Bottom alignment and identical neighboring elements

Configure Row Spacing

setRowSpacingRule selects the spacing rule for rows within the array. setRowSpacing supplies a numeric value for an explicit spacing rule and is ignored by the preset rules.

For exact spacing, the value is measured in points. For proportional spacing, it is measured in half-lines: the value 3 in the example specifies 1.5 lines. Set both properties when specifying an explicit value; changing the numeric value alone does not select a spacing rule.

The example below saves five presentations with the same equations, alignment, and font settings. The first three use presets; the last two show explicit values.

use aspose\slides\FontData;
use aspose\slides\MathArray;
use aspose\slides\MathBlock;
use aspose\slides\MathJustification;
use aspose\slides\MathRowSpacingRule;
use aspose\slides\MathVerticalAlignment;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$createText = static function (string $value) {
    $text = new MathematicalText($value);
    $text->getFormat()->setFontHeight(24);
    $text->getFormat()->setLatinFont(new FontData("Cambria Math"));
    return $text;
};

$settings = [
    "SingleLineGap" => [MathRowSpacingRule::SingleLineGap, 0],
    "OneAndAHalfLineGap" => [MathRowSpacingRule::OneAndAHalfLineGap, 0],
    "TwoLineGap" => [MathRowSpacingRule::TwoLineGap, 0],
    "Exactly" => [MathRowSpacingRule::Exactly, 20],
    "Multiple" => [MathRowSpacingRule::Multiple, 3],
];

foreach ($settings as $name => [$rule, $spacing]) {
    $presentation = new Presentation();
    try {
        $mathShape = $presentation->getSlides()->get_Item(0)->getShapes()->addMathShape(20, 20, 600, 300);
        $paragraph = $mathShape->getTextFrame()->getParagraphs()->get_Item(0);
        $paragraph->getParagraphFormat()->setSpaceBefore(0);
        $paragraph->getParagraphFormat()->setSpaceAfter(0);
        $mathParagraph = $paragraph->getPortions()->get_Item(0)->getMathParagraph();
        $mathParagraph->setJustification(MathJustification::LeftJustified);

        $firstRow = $createText("x+y=3");
        $equationArray = new MathArray($firstRow);
        foreach (["x-y=1", "x=2"] as $value) {
            $row = $createText($value);
            $equationArray->getArguments()->add($row);
        }
        $equationArray->setBaseJustification(MathVerticalAlignment::Center);
        $equationArray->setRowSpacingRule($rule);
        $equationArray->setRowSpacing($spacing);
        $leftText = $createText("A=");
        $rightText = $createText("=B");
        $equation = (new MathBlock($leftText))->join($equationArray)->join($rightText);
        $mathParagraph->add($equation);
        $presentation->save("equation-array-$name.pptx", SaveFormat::Pptx);
    } finally {
        $presentation->dispose();
    }
}

Array row spacing is separate from paragraph spacing. setSpaceBefore and setSpaceAfter add space around the containing paragraph, not between array rows. Likewise, MathParagraph::setJustification positions the whole math paragraph horizontally; it does not replace the array’s vertical alignment setting.

Distribute Equation Columns Horizontally

Use setMaximumDistribution to expand an equation array to the width available in its container, such as a text frame. Use setObjectDistribution to spread the equation columns to the edges of the array itself. For vertical alignment relative to surrounding text, use setBaseJustification. For vertical spacing between rows, use setRowSpacingRule and setRowSpacing.

The example places the same three rows in four equal-sized frames. In x&=1&y&=2, the first and third & align the equals signs within their respective columns. The middle & separates the columns so PowerPoint can insert space between them. All four arrays use the same font size, row spacing, and paragraph formatting.

use aspose\slides\MathArray;
use aspose\slides\MathBlock;
use aspose\slides\MathJustification;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
use aspose\slides\SlideSizeScaleType;
use aspose\slides\TextAutofitType;

$createRow = static function (string $expression) {
    $text = new MathematicalText($expression);
    $text->getFormat()->setFontHeight(20);
    return $text;
};

$presentation = new Presentation();
try {
    $presentation->getSlideSize()->setSize(720, 440, SlideSizeScaleType::DoNotScale);
    $shapes = $presentation->getSlides()->get_Item(0)->getShapes();

    $labels = ["Both off", "Maximum only", "Object only", "Both on"];
    $maximumDistribution = [false, true, false, true];
    $objectDistribution = [false, false, true, true];

    $y = 5;
    foreach ($labels as $i => $labelText) {
        $label = $shapes->addAutoShape(ShapeType::Rectangle, 5, $y, 145, 104);
        $label->getTextFrame()->setText($labelText);
        $label->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0)->getPortionFormat()->setFontHeight(17);

        $frame = $shapes->addMathShape(155, $y, 550, 104);
        $frame->getTextFrame()->getTextFrameFormat()->setAutofitType(TextAutofitType::None);

        $mathParagraph = $frame->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();
        $mathParagraph->setJustification(MathJustification::LeftJustified);

        $firstRow = $createRow("x&=1&y&=2");
        $secondRow = $createRow("a+b+c&=12&z&=u+v");
        $thirdRow = $createRow("k&=0&t&=3");
        $array = new MathArray($firstRow);
        $array->getArguments()->add($secondRow);
        $array->getArguments()->add($thirdRow);
        $array->setMaximumDistribution($maximumDistribution[$i]);
        $array->setObjectDistribution($objectDistribution[$i]);

        $mathParagraph->add(new MathBlock($array));
        $y += 108;
    }
    $presentation->save("equation-array-distribution.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

In PowerPoint, Both off and Object only look alike because the compact array has no extra width to distribute. With Maximum only, PowerPoint leaves space on both sides of the array’s contents and between the columns. With Both on, the outer columns reach the edges of the available width and the extra space falls between them.

PowerPoint comparison of four distribution settings, showing compact columns, space around and between columns, and columns spread to opposite edges

Add Trigonometric Functions

Use asArgumentOfFunction when the argument is the current element and the function name is known.

The trigonometric function cos applied to 2x

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 100);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $cosine = (new MathematicalText("2x"))
        ->asArgumentOfFunction(MathFunctionsOfOneArgument::Cos);

    $mathParagraph->add(new MathBlock($cosine));

    $presentation->save("trigonometric-function.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Add Subscripts and Superscripts

Use the subscript and superscript helpers for indexes and powers. When the indexes must appear on the left side of the base, use setSubSuperscriptOnTheLeft.

A capital Y with left-side subscript 1 and superscript n

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 100);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $scripts = (new MathematicalText("Y"))
        ->setSubSuperscriptOnTheLeft("1", "n");

    $mathParagraph->add(new MathBlock($scripts));

    $presentation->save("subscript-superscript.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Align Right Subscripts and Superscripts

When both scripts belong to the same base, use MathRightSubSuperscriptElement. Its setAlignScripts method controls their horizontal positions: false (the default) lets them follow the contour of the base, while true aligns the scripts horizontally with each other.

This example places two copies of the same editable expression side by side. Both use mathematical italic f (U+1D453), a lower script of 1, an upper script of 2, and Cambria Math at 72 points. The sloping base makes the difference visible in PowerPoint. Install Cambria Math before running the example.

use aspose\slides\FontData;
use aspose\slides\MathBlock;
use aspose\slides\MathematicalText;
use aspose\slides\MathRightSubSuperscriptElement;
use aspose\slides\PortionFormat;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\SlideSizeScaleType;

$presentation = new Presentation();
try {
    $presentation->getSlideSize()->setSize(900, 250, SlideSizeScaleType::DoNotScale);
    $slide = $presentation->getSlides()->get_Item(0);

    $format = new PortionFormat();
    $format->setFontHeight(72);
    $font = new FontData("Cambria Math");
    $format->setLatinFont($font);

    for ($i = 0; $i < 2; $i++) {
        $left = 40 + $i * 440;
        $shape = $slide->getShapes()->addMathShape($left, 75, 380, 150);

        $baseText = new MathematicalText("\u{1D453}", $format);
        $subscript = new MathematicalText("1", $format);
        $superscript = new MathematicalText("2", $format);
        $scripts = new MathRightSubSuperscriptElement($baseText, $subscript, $superscript);
        $scripts->setAlignScripts($i === 1);

        $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
        $portion->getPortionFormat()->setFontHeight($format->getFontHeight());
        $portion->getPortionFormat()->setLatinFont($format->getLatinFont());
        $mathBlock = new MathBlock($scripts);
        $portion->getMathParagraph()->add($mathBlock);
    }

    $presentation->save("aligned-scripts.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

Two editable expressions in PowerPoint with setAlignScripts set to false on the left and true on the right

On the left, the lower script starts farther left than the upper script, following the base contour. On the right, the two scripts align horizontally with each other.

Add Delimiters

Use enclose to put an expression inside delimiters. You can also set a separator character for delimiter expressions that contain several elements.

A delimiter expression containing x, y, and z separated by vertical bars

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 100);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $delimiter = (new MathematicalText("x"))
        ->join("y")
        ->join("z")
        ->enclose(new Java("java.lang.Character", "<"), new Java("java.lang.Character", ">"));
    $delimiter->setSeparatorCharacter(new Java("java.lang.Character", "|"));

    $mathParagraph->add(new MathBlock($delimiter));

    $presentation->save("delimiters.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Size and Align Delimiters

Pass true to setGrowToMatchOperandHeight to let the parentheses grow around a tall operand, or pass false to keep them at their normal size. Use setDelimiterShape with one of two MathDelimiterShape values. Centered centers the parentheses on the math axis, which runs through the middle of the equals sign. Match aligns them with the enclosed content. Both settings affect only the delimiters. The expression inside stays the same.

The example places a fraction in the exponent of x so the expression extends farther above the baseline than below it. All four equations use the same parentheses and font settings.

use aspose\slides\MathDelimiterShape;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);
    $opening = new Java("java.lang.Character", "(");
    $closing = new Java("java.lang.Character", ")");
    for ($row = 0; $row < 2; $row++) {
        for ($column = 0; $column < 2; $column++) {
            $fraction = (new MathematicalText("a + b"))->divide("c + d");
            $power = (new MathematicalText("x"))->setSuperscript($fraction);
            $delimiter = $power->enclose($opening, $closing);
            $delimiter->setGrowToMatchOperandHeight($row === 0);
            $delimiter->setDelimiterShape($column === 0 ? MathDelimiterShape::Centered : MathDelimiterShape::Match);

            $mathShape = $slide->getShapes()->addMathShape(20 + 330 * $column, 20 + 120 * $row, 300, 100);
            $portion = $mathShape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
            $portion->getPortionFormat()->setFontHeight(32);
            $equation = (new MathematicalText("y = "))->join($delimiter);
            $portion->getMathParagraph()->add($equation);
        }
    }
    $presentation->save("delimiter-sizing.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

In PowerPoint, compare the rows to see the effect of growth. In the top row, the parentheses grow to enclose the exponent and look alike for both shapes. In the bottom row, growth is off. The smaller parentheses on the left (Centered) align with the equals sign, while those on the right (Match) sit higher around the expression.

Four equations in PowerPoint with delimiter growth enabled above and disabled below, and Centered on the left and Match on the right

Add a Border Box

Call toBorderBox on a fraction to frame the entire expression. The returned MathBorderBox shows all four sides by default. Use setHideTop, setHideBottom, setHideLeft, and setHideRight to remove individual sides.

The example places six copies of the same fraction on one slide. To show cancellation, hide all four sides and pass true to setStrikethroughBottomLeftToTopRight for a rising diagonal (↗) or setStrikethroughTopLeftToBottomRight for a falling diagonal (↘). You can also use setStrikethroughHorizontal or setStrikethroughVertical with any combination of visible sides.

use aspose\slides\MathBlock;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\SlideSizeScaleType;

$presentation = new Presentation();
try {
    $presentation->getSlideSize()->setSize(540, 220, SlideSizeScaleType::DoNotScale);
    $slide = $presentation->getSlides()->get_Item(0);

    $addFraction = function ($x, $y, $hideBorder) use ($slide) {
        $fraction = (new MathematicalText("x+1"))->divide("y+2");
        $box = $fraction->toBorderBox();
        $box->setHideTop($hideBorder);
        $box->setHideBottom($hideBorder);
        $box->setHideLeft($hideBorder);
        $box->setHideRight($hideBorder);

        $shape = $slide->getShapes()->addMathShape($x, $y, 160, 90);
        $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
        $portion->getPortionFormat()->setFontHeight(28);
        $mathBlock = new MathBlock($box);
        $portion->getMathParagraph()->add($mathBlock);
        return $box;
    };

    $addFraction(10, 10, false);

    $partial = $addFraction(190, 10, false);
    $partial->setHideTop(true);
    $partial->setHideRight(true);

    $addFraction(370, 10, true)->setStrikethroughBottomLeftToTopRight(true);
    $addFraction(10, 120, true)->setStrikethroughTopLeftToBottomRight(true);
    $addFraction(190, 120, true)->setStrikethroughHorizontal(true);
    $addFraction(370, 120, false)->setStrikethroughVertical(true);

    $presentation->save("border-box.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

Six editable fractions in PowerPoint. Top row: full border, bottom and left sides, rising diagonal. Bottom row: falling diagonal, horizontal strike, vertical strike with a full border.

On this fraction, the horizontal strike overlaps the fraction bar. The vertical strike crosses both the numerator and the denominator while the surrounding border stays visible. These lines decorate the whole expression. Ordinary text strikethrough applies to characters in a text run. After reopening the presentation in PowerPoint, you can still edit the numerator and denominator independently.

Control Visibility and Layout with Phantom Elements

Wrap an expression in MathPhantom to control its visibility and the space it contributes to an equation independently. The MathPhantom methods control the following:

Method Effect
setShow Pass false to hide the expression. Its dimensions still contribute to layout unless the corresponding methods below receive true.
setZeroWidth Treat the expression’s horizontal width as zero, allowing neighboring elements to move closer together.
setZeroAsc Treat its ascent, the height above the baseline, as zero. This can reduce the space reserved above neighboring elements.
setZeroDesc Treat its descent, the depth below the baseline, as zero. This can move a fraction bar or other content below the expression closer to its neighbors.

The baseline is the reference line on which ordinary mathematical letters sit. Hiding content does not remove its dimensions, and treating a dimension as zero does not delete the expression. The underlying expression remains available through getBase. Pass true to setShow to display it again; the dimension settings remain unchanged.

The example below creates five side-by-side variants: a visible fraction, a hidden fraction that reserves space, and three hidden fractions with one dimension treated as zero. Each variant uses the same surrounding expression and Cambria Math at 24 points. All equation shapes have the same top position, marked by the gray guide. Placing the phantom in the numerator of an outer fraction makes the vertical layout changes easier to see.

use aspose\slides\FillType;
use aspose\slides\FontData;
use aspose\slides\MathBlock;
use aspose\slides\MathFraction;
use aspose\slides\MathPhantom;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;
use aspose\slides\ShapeType;
use aspose\slides\SlideSizeScaleType;
use aspose\slides\TextAnchorType;

$createText = static function (string $value) {
    $text = new MathematicalText($value);
    $text->getFormat()->setFontHeight(24);
    $text->getFormat()->setLatinFont(new FontData("Cambria Math"));
    return $text;
};

$presentation = new Presentation();
try {
    $presentation->getSlideSize()->setSize(1000, 180, SlideSizeScaleType::DoNotScale);
    $slide = $presentation->getSlides()->get_Item(0);

    $labels = ["Visible", "Hidden: reserves space", "Hidden: ZeroWidth", "Hidden: ZeroAsc", "Hidden: ZeroDesc"];

    $guide = $slide->getShapes()->addAutoShape(ShapeType::Line, 10, 60, 980, 0);
    $guide->getLineFormat()->getFillFormat()->setFillType(FillType::Solid);
    $guide->getLineFormat()->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->LIGHT_GRAY);

    foreach ($labels as $i => $labelText) {
        $left = 10 + $i * 200;

        $label = $slide->getShapes()->addAutoShape(ShapeType::Rectangle, $left, 10, 190, 30);
        $label->getFillFormat()->setFillType(FillType::NoFill);
        $label->getLineFormat()->getFillFormat()->setFillType(FillType::NoFill);
        $label->getTextFrame()->setText($labelText);

        $labelFormat = $label->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0)->getPortionFormat();
        $labelFormat->setFontHeight(14);
        $labelFormat->getFillFormat()->setFillType(FillType::Solid);
        $labelFormat->getFillFormat()->getSolidFillColor()->setColor(java("java.awt.Color")->BLACK);

        $fractionNumerator = $createText("a+b");
        $fractionDenominator = $createText("c+d");
        $fraction = new MathFraction($fractionNumerator, $fractionDenominator);
        $phantom = new MathPhantom($fraction);
        $phantom->setShow($i === 0);
        $phantom->setZeroWidth($i === 2);
        $phantom->setZeroAsc($i === 3);
        $phantom->setZeroDesc($i === 4);

        $leftText = $createText("x+");
        $rightText = $createText("+y");
        $numerator = (new MathBlock($leftText))->join($phantom)->join($rightText);
        $denominator = $createText("z");
        $equation = new MathFraction($numerator, $denominator);

        $shape = $slide->getShapes()->addMathShape($left, 60, 190, 100);
        $shape->getTextFrame()->getTextFrameFormat()->setAnchoringType(TextAnchorType::Top);

        $mathPortion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
        $mathParagraph = $mathPortion->getMathParagraph();
        $mathBlock = new MathBlock($equation);
        $mathParagraph->add($mathBlock);
    }

    $presentation->save("math-phantom.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

Five equations in PowerPoint comparing a visible fraction, a hidden fraction that reserves space, and hidden fractions with ZeroWidth, ZeroAsc, or ZeroDesc enabled

Group Terms

Use group to place a grouping character above or below an expression. Add a limit to label the grouped terms.

The expression x plus y grouped with the label any text below it

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 120);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $grouped = (new MathematicalText("x + y"))
        ->group(new Java("java.lang.Character", "\u{23DF}"), MathTopBotPositions::Bottom, MathTopBotPositions::Top)
        ->setLowerLimit("any text");

    $mathParagraph->add(new MathBlock($grouped));

    $presentation->save("grouped-terms.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Control Baseline Alignment

Use setPosition to place the grouping character above or below the expression. Use setVerticalJustification to align the top or bottom part of the group with the baseline of the surrounding math text.

The following example places the same underbrace (U+23DF) below x+y in both equations. Compare the position of x+y relative to a= and +b as the last argument to group changes.

use aspose\slides\MathematicalText;
use aspose\slides\MathTopBotPositions;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $addEquation = function ($x, $justification) use ($slide) {
        $underbrace = new Java("java.lang.Character", "\u{23DF}");
        $group = (new MathematicalText("x+y"))->group($underbrace, MathTopBotPositions::Bottom, $justification);
        $equation = (new MathematicalText("a="))->join($group)->join("+b");

        $shape = $slide->getShapes()->addMathShape($x, 100, 300, 100);
        $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
        $portion->getMathParagraph()->add($equation);
    };

    $addEquation(40, MathTopBotPositions::Top);
    $addEquation(380, MathTopBotPositions::Bottom);

    $presentation->save("GroupingCharacter.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

PowerPoint displays the two equations side by side.

VerticalJustification = Top VerticalJustification = Bottom
The expression x+y shares the baseline of the surrounding text. The expression x+y sits above the baseline of the surrounding text.
  • Top aligns x+y with the surrounding text. The underbrace extends below the baseline.
  • Bottom raises x+y above the baseline. The underbrace now sits closer to the baseline of the surrounding text.

These settings affect only the grouped terms within the equation. They do not move the text within its frame. To add a label above or below the group, use setUpperLimit or setLowerLimit.

Format Math Elements

You can place a bar above or below a single term or a whole expression. You can also format text within an equation, for example by choosing a symbol font for one character or changing the font size throughout the equation.

Apply an Overbar to an Expression

Use formatting helpers only where they clarify the formula. For example, overbar places a bar above a math element.

A math expression ABC with an overbar

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $mathShape = $slide->getShapes()->addMathShape(20, 20, 700, 100);
    $mathParagraph = $mathShape->getTextFrame()->getParagraphs()
        ->get_Item(0)->getPortions()->get_Item(0)->getMathParagraph();

    $overbar = (new MathematicalText("ABC"))->overbar();

    $mathParagraph->add(new MathBlock($overbar));

    $presentation->save("overbar.pptx", SaveFormat::Pptx);
} finally {
    if (!java_is_null($presentation)) {
        $presentation->dispose();
    }
}

Apply an Underbar to an Expression

underbar places a bar beneath the element you call it on. To extend the bar across all of F + 1/y, create the fraction with divide, assemble the expression with join, and then call underbar on the completed block. To place the bar under just F, call underbar on F before joining the remaining terms.

use aspose\slides\MathBlock;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

class UnderbarExample {
    public function unitFraction() {
        return (new MathematicalText("1"))->divide("y");
    }

    public function addEquation($slide, $x, $block) {
        $shape = $slide->getShapes()->addMathShape($x, 100, 260, 100);
        $portion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);
        $portion->getMathParagraph()->add($block);
    }
}

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);

    $example = new UnderbarExample();
    $sum = (new MathematicalText("F"))->join("+")->join($example->unitFraction());
    $wholeExpression = new MathBlock($sum->underbar());
    $firstOperandOnly = (new MathematicalText("F"))->underbar()->join("+")->join($example->unitFraction());

    $example->addEquation($slide, 80, $wholeExpression);
    $example->addEquation($slide, 380, $firstOperandOnly);

    $presentation->save("underbar-scope.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

PowerPoint equations side by side, with a bar spanning the entire sum on the left and only F on the right

Left: underbar on the whole expression. Right: underbar on F only.

The bar is part of the equation structure. Text underline formatting applies to individual characters, and a manually drawn line is a separate slide shape.

Use a Symbol Font in an Equation

To insert a Wingdings arrow between two operands, create a separate MathematicalText element for the arrow. Call setSymbolFont on the format returned by MathematicalText::getFormat. This gives only the arrow the Wingdings font and preserves the formatting of both operands.

Choose the character code and symbol font together. Wingdings displays U+F0E0 as a right arrow. Another font may display a different glyph at that code point or have no glyph for it.

use aspose\slides\FontData;
use aspose\slides\MathBlock;
use aspose\slides\MathematicalText;
use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

$presentation = new Presentation();
try {
    $slide = $presentation->getSlides()->get_Item(0);
    
    $shape = $slide->getShapes()->addMathShape(20, 20, 240, 90);
    $mathPortion = $shape->getTextFrame()->getParagraphs()->get_Item(0)->getPortions()->get_Item(0);

    $left = new MathematicalText("A");
    $arrow = new MathematicalText("\u{F0E0}");
    $right = new MathematicalText("B");
    $arrow->getFormat()->setSymbolFont(new FontData("Wingdings"));

    $block = new MathBlock();
    $block->add($left);
    $block->add($arrow);
    $block->add($right);
    $mathPortion->getMathParagraph()->add($block);

    $presentation->save("symbol-font-arrow.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

PowerPoint displays the saved equation as shown below. All three elements remain editable.

Editable equation with a Wingdings right arrow between A and B

LoadOptions::setDefaultSymbolFont configures the default symbol font when loading a presentation. Assigning a symbol font to an individual element does not embed the font in the presentation. Wingdings must be available in the rendering environment.

Format Text in an Existing Equation

To format text throughout an existing equation, traverse each math block’s element tree. MathElementBase::getChildren returns only the immediate children, so call it recursively to reach text inside fractions, scripts, radicals, and other nested structures. Check the current element as well as its children to include the starting element when it is MathematicalText.

This example assumes that input.pptx contains an equation such as z = xᵢ / ∛y, with a fraction containing a subscript in its numerator and a radical in its denominator. Processing only the block’s top-level elements would miss the text inside the fraction. The example finds mathematical portions in slide text frames, accesses their blocks through MathPortion::getMathParagraph, and uses setFontHeight to set the font size to 28 points through each text element’s getFormat method.

use aspose\slides\Presentation;
use aspose\slides\SaveFormat;

function formatMathText($element, $mathematicalTextClass) {
    if (java_instanceof($element, $mathematicalTextClass)) {
        $element->getFormat()->setFontHeight(28);
    }

    foreach ($element->getChildren() as $child) {
        formatMathText($child, $mathematicalTextClass);
    }
}

$mathematicalTextClass = new JavaClass("com.aspose.slides.MathematicalText");
$autoShapeClass = new JavaClass("com.aspose.slides.IAutoShape");
$mathPortionClass = new JavaClass("com.aspose.slides.IMathPortion");

$presentation = new Presentation("input.pptx");
try {
    for ($slideIndex = 0; $slideIndex < java_values($presentation->getSlides()->size()); $slideIndex++) {
        $slide = $presentation->getSlides()->get_Item($slideIndex);
        for ($shapeIndex = 0; $shapeIndex < java_values($slide->getShapes()->size()); $shapeIndex++) {
            $shape = $slide->getShapes()->get_Item($shapeIndex);
            if (!java_instanceof($shape, $autoShapeClass)) {
                continue;
            }

            $textFrame = $shape->getTextFrame();
            if (java_is_null($textFrame)) {
                continue;
            }

            for ($paragraphIndex = 0; $paragraphIndex < java_values($textFrame->getParagraphs()->getCount()); $paragraphIndex++) {
                $paragraph = $textFrame->getParagraphs()->get_Item($paragraphIndex);
                for ($portionIndex = 0; $portionIndex < java_values($paragraph->getPortions()->getCount()); $portionIndex++) {
                    $portion = $paragraph->getPortions()->get_Item($portionIndex);
                    if (java_instanceof($portion, $mathPortionClass)) {
                        for ($blockIndex = 0; $blockIndex < java_values($portion->getMathParagraph()->getCount()); $blockIndex++) {
                            $block = $portion->getMathParagraph()->get_Item($blockIndex);
                            formatMathText($block, $mathematicalTextClass);
                        }
                    }
                }
            }
        }
    }

    $presentation->save("formatted-equations.pptx", SaveFormat::Pptx);
} finally {
    $presentation->dispose();
}

The saved presentation contains the updated text formatting at every level of each processed equation, while preserving its text content and mathematical structure.

Quick Reference

Task Main API
Create math text MathematicalText
Combine elements join
Create fractions divide
Add superscript or subscript setSuperscript, setSubscript
Add functions function, asArgumentOfFunction
Add radicals 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

Can I edit an existing PowerPoint equation?

Yes. Open the presentation, find the shape that contains a MathPortion, call getMathParagraph, and update the math blocks in that paragraph.

Are equations saved as editable PowerPoint math?

Yes. When you save to PPTX, Aspose.Slides writes the equation as editable Office math content.

Can I export equations to LaTeX?

Yes. Get the equation’s MathParagraph from its MathPortion, and call MathParagraph::toLatex to export it directly. For a complete example, see Export Math Equations from Presentations in PHP via Java.