在 Java 中向 PowerPoint 演示文稿添加数学公式

概述

PowerPoint 将公式存储为 Office Math Markup Language (OMML)。使用 Aspose.Slides for Java,您可以以编程方式创建相同类型的数学内容:分数、根式、函数、极限、N 元运算符、矩阵、数组以及格式化的数学块。

在 PowerPoint 中,用户通常通过 插入 > 公式 添加公式:

PowerPoint 插入选项卡中选中的公式命令

结果是幻灯片上的可编辑数学文本:

包含可编辑数学公式的 PowerPoint 幻灯片

Aspose.Slides 通过三个主要对象构建该数学文本:

下面的大多数示例使用 MathematicalText 和来自 IMathElement 的流畅方法以保持代码简洁易读。

有关 MathML 导出场景,请参阅 Export Math Equations from Presentations in Java。

创建公式

此示例使用 addMathShape 创建数学形状并添加勾股定理:

公式 c² = a² + b² 的图示

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 120);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathBlock 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 {
    presentation.dispose();
}

组合数学块

当公式的部分作为 IMathBlock 对象独立构建时,使用 joinBlock 将它们组合。示例在左块中构建 c² =,在右块中构建 a² + b²。setSuperscript 为这三个幂创建可编辑的数学上标。

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape shape = slide.getShapes().addMathShape(20, 20, 600, 100);
    IMathPortion mathPortion = (IMathPortion) shape.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0);
    IMathParagraph mathParagraph = mathPortion.getMathParagraph();

    MathBlock leftBlock = new MathBlock();
    leftBlock.add(new MathematicalText("c").setSuperscript("2"));
    leftBlock.add(new MathematicalText("="));

    MathBlock rightBlock = new MathBlock();
    rightBlock.add(new MathematicalText("a").setSuperscript("2"));
    rightBlock.add(new MathematicalText("+"));
    rightBlock.add(new MathematicalText("b").setSuperscript("2"));

    IMathBlock combinedBlock = leftBlock.joinBlock(rightBlock);
    mathParagraph.add(combinedBlock);

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

joinBlock 返回自身 leftBlock,现在按顺序包含了两个部分,并将 rightBlock 置为空。仅一次将组合后的块添加到 IMathParagraph 中。重新打开 equation.pptx 后,段落只包含一个块,表示 c² = a² + b²,三个幂仍保留为数学上标。

将 add 写作 leftBlock.add(rightBlock) 会尝试将一个块直接嵌套在另一个块内部,从而抛出 InvalidOperationException。

添加分数

使用 divide 创建分数。您可以使用 MathFractionTypes 选择分数样式。

一个倾斜的数学分数,显示 1 除以 x

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 100);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathFraction fraction = new MathematicalText("1")
            .divide("x", MathFractionTypes.Skewed);

    mathParagraph.add(new MathBlock(fraction));

    presentation.save("fraction.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

对于堆叠分数,使用 MathFractionTypes.Bar:

import com.aspose.slides.*;

IMathFraction stackedFraction = new MathematicalText("x + 1").divide("y - 1", MathFractionTypes.Bar);

添加根式

使用 radical 创建平方根、立方根或其他根式。当前元素成为底数,参数成为指数。

一个 n 次根式,x 位于根号下方

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 100);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathRadical radical = new MathematicalText("x")
            .radical("n");

    mathParagraph.add(new MathBlock(radical));

    presentation.save("radical.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

显示或隐藏平方根的指数

平方根可以显式显示 2,或使用常规的 √x 记法。IMathRadical 的 setHideDegree 方法控制显示哪种形式。两种形式均保留指数 2 和被开方数 x,在可编辑公式中保持不变。

左侧显示指数的相同平方根,右侧隐藏指数

示例将相同的平方根保存两次。visible-degree.pptx 中指数可见,hidden-degree.pptx 中指数隐藏。

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);
    
    IMathRadical radical = new MathematicalText("x").radical("2");

    IAutoShape shape = slide.getShapes().addMathShape(20, 20, 200, 100);
    IMathPortion portion = (IMathPortion) 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();
}

添加函数和极限

使用 asArgumentOfFunction 或 function 添加 sin(x)、log(x) 等函数或自定义函数名。对于极限,在 MathLimit 中放置 lim,或使用 setLowerLimit。

x 趋于无穷大的极限图示

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 100);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathFunction limit = new MathematicalText("lim")
            .setLowerLimit("x\u2192\u221E")
            .function("x");

    mathParagraph.add(new MathBlock(limit));

    presentation.save("functions-and-limits.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

对于自定义函数名,将函数名设为当前元素并调用 function 并传入其参数:

import com.aspose.slides.*;

IMathFunction customFunction = new MathematicalText("f").function("x + 1");

添加 N 元运算符和积分

使用 nary 处理求和、并集、交集等大型运算符。使用 integral 添加积分。两者均可设置上下限。

带上下限的求和示意图

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 120);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathBlock summationBase = new MathematicalText("x")
            .setSuperscript("k")
            .join(new MathematicalText("a").setSuperscript("n-k"));

    IMathNaryOperator summation = summationBase.nary(MathNaryOperatorTypes.Summation, "k=0", "n");

    mathParagraph.add(new MathBlock(summation));

    presentation.save("nary-operators.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

N 元运算符用于带可选上下限的大型运算符。诸如 +、-、= 等简单运算符通常使用 MathematicalText 添加并合并到表达式中。

对于积分,使用 integral:

import com.aspose.slides.*;

IMathBlock integralBase = new MathematicalText("x").join(new MathematicalText("dx").toBox());
IMathNaryOperator integral = integralBase.integral(MathIntegralTypes.Simple, "0", "1");

创建复合运算符

要将 == 视为两个操作数之间的单一运算符,请在包含两个等号的 MathematicalText 上调用 toBox。在生成的 IMathBox 上调用 setOperatorEmulator 并传入 true,使该组合作为数学运算符。默认值为 false。

setNoBreak 控制盒内的换行。示例显式将此选项设为默认的 true,以保持两个等号在同一行。其余公式仍可换行。

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);
    
    IAutoShape shape = slide.getShapes().addMathShape(20, 20, 300, 60);
    IMathPortion portion = (IMathPortion) shape.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0);

    IMathBox compoundOperator = new MathematicalText("==").toBox();
    compoundOperator.setOperatorEmulator(true);
    compoundOperator.setNoBreak(true);

    IMathBlock equation = new MathematicalText("a").join(compoundOperator).join(new MathematicalText("b"));
    portion.getMathParagraph().add(equation);

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

添加矩阵

使用 MathMatrix 管理行列。矩阵默认不包含括号,如需圆括号、方括号或花括号,请自行在矩阵外部添加。

一个两行的数学矩阵,其中一个单元格为空

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 120);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    MathMatrix 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 {
    presentation.dispose();
}

编辑已有矩阵

假设线性代数课程从 matrix.pptx 中的系数矩阵开始,该文件由前面的示例保存。接下来练习时,保留第一个公式,替换第二个为两个新公式,并修改变量集。通过 IMathMatrix 打开已有矩阵,以保留仍然有效的系数。

原始两行系数矩阵,第一行含 1、x 和空单元格,第二行含 x、2、y

行列索引从零开始,指向每次调用时的矩阵状态。将在索引 1 前插入行会将原第二行移动到索引 2;在索引 2 后插入会追加一行。删除第 2 行会移除原第二个公式并将追加的行上移一位。列的移动方式相同。

import com.aspose.slides.*;

Presentation presentation = new Presentation("matrix.pptx");
try {
    IAutoShape shape = (IAutoShape) presentation.getSlides().get_Item(0).getShapes().get_Item(0);
    IMathPortion portion = (IMathPortion) shape.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0);
    IMathMatrix matrix = (IMathMatrix) portion.getMathParagraph().get_Item(0).get_Item(0);

    matrix.insertRowBefore(1);
    matrix.insertRowAfter(2);
    matrix.deleteRow(2);

    matrix.insertColumnBefore(1);
    matrix.insertColumnAfter(3);
    matrix.deleteColumn(3);

    // 新单元格最初为 null。先设置非零系数。
    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"));
    for (int row = 0; row < matrix.getRowCount(); row++) {
        for (int column = 0; column < matrix.getColumnCount(); column++) {
            if (matrix.get_Item(row, column) == null) {
                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 将首列左对齐。setColumnsAlignment 将从索引 1 开始的连续三列右对齐。在 updated-matrix.pptx 中,矩阵包含三个公式和四个变量。原始第一行的系数 1 与 x 现在出现在第一列和第三列。

更新后的三行矩阵,显示行 1,0,x,0;12,1,0,0;以及 0,0,10,1

设置矩阵行列间距

示例创建一个 2 × 2 的分数矩阵,最小列宽 48 点,列间距 12 点,行间距 1.5 行。

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape shape = slide.getShapes().addMathShape(20, 40, 300, 180);
    IMathPortion portion = (IMathPortion) shape.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0);

    MathMatrix 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 以 twip 为单位设置每列的最小宽度(20 twip = 1 点)。setColumnGap 为相邻列之间添加间距。两者共同决定从一列起始到下一列起始的距离。

setColumnGapRule 与 setRowGapRule 用于为各方向选择 MathSpacingRules 的值。使用 Exactly 时,两个间距值均以 twip 计量。使用 Multiple 时,传递给 setColumnGap 的每个单位代表 0.5 em,传递给 setRowGap 的每个单位代表半行。其他列间距规则会忽略传递给 setColumnGap 的值。

这些设置仅在矩阵内部生效。段落间距控制外围文本布局。有关公式阵列中行间距的设置,请参阅 Configure Row Spacing。

添加公式阵列

当需要对齐公式或垂直堆叠表达式时,使用 toMathArray。

一个垂直的数学阵列,x 在上方,y 在下方

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 140);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathArray equationArray = new MathematicalText("x")
            .join("y")
            .toMathArray();

    mathParagraph.add(new MathBlock(equationArray));

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

将阵列与周围元素对齐

setBaseJustification 控制阵列相对于其旁边的数学元素的垂直对齐方式。下面的示例比较了基于第一行、阵列中心和最后一行的对齐方式。

示例创建了三个相同的阵列,每个都有三行,并在两侧放置相邻元素 A= 与 =B。所有数学文本使用 Cambria Math,字号 24 点。唯一变化的是阵列的对齐方式。

import com.aspose.slides.*;
import java.awt.Color;

class MathTextFactory {
    MathematicalText createText(String value) {
        MathematicalText text = new MathematicalText(value);
        text.getFormat().setFontHeight(24);
        text.getFormat().setLatinFont(new FontData("Cambria Math"));
        return text;
    }
}

MathTextFactory factory = new MathTextFactory();
Presentation presentation = new Presentation();
try {
    presentation.getSlideSize().setSize(780, 200, SlideSizeScaleType.DoNotScale);
    ISlide slide = presentation.getSlides().get_Item(0);
    
    int[] alignments = { MathVerticalAlignment.Top, MathVerticalAlignment.Center, MathVerticalAlignment.Bottom };
    String[] alignmentNames = { "Top", "Center", "Bottom" };

    for (int i = 0; i < alignments.length; i++) {
        IAutoShape label = slide.getShapes().addAutoShape(ShapeType.Rectangle, 20 + i * 260, 10, 240, 30);
        label.getFillFormat().setFillType(FillType.NoFill);
        label.getLineFormat().getFillFormat().setFillType(FillType.NoFill);
        label.getTextFrame().setText(alignmentNames[i]);
        IPortionFormat labelFormat = label.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0).getPortionFormat();
        labelFormat.setFontHeight(16);
        labelFormat.getFillFormat().setFillType(FillType.Solid);
        labelFormat.getFillFormat().getSolidFillColor().setColor(Color.BLACK);

        IAutoShape mathShape = slide.getShapes().addMathShape(20 + i * 260, 60, 240, 130);
        mathShape.getTextFrame().getTextFrameFormat().setAnchoringType(TextAnchorType.Top);
        IMathParagraph mathParagraph = ((IMathPortion) mathShape.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0)).getMathParagraph();
        mathParagraph.setJustification(MathJustification.LeftJustified);

        IMathElement[] rows = { factory.createText("x+y=3"), factory.createText("x-y=1"), factory.createText("x=2") };
        MathArray equationArray = new MathArray(rows[0]);
        equationArray.getArguments().add(rows[1]);
        equationArray.getArguments().add(rows[2]);
        equationArray.setBaseJustification(alignments[i]);
        MathematicalText leftText = factory.createText("A=");
        MathematicalText rightText = factory.createText("=B");
        IMathBlock equation = new MathBlock(leftText).join(equationArray).join(rightText);
        mathParagraph.add(equation);
    }

    presentation.save("equation-array-alignment.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

下面的对比图展示了在 PowerPoint 中保存的演示文稿。请注意每个阵列旁边 A= 与 =B 的位置。

PowerPoint 中的公式阵列,分别展示顶部、居中和底部对齐,以及相同的相邻元素

配置行间距

setRowSpacingRule 选择阵列内部行的间距规则。setRowSpacing 为显式间距规则提供数值,该数值会被预设规则忽略。

对于精确间距,数值以点为单位。对于比例间距,数值以半行为单位:示例中 3 表示 1.5 行。指定显式数值时,需要同时设置两属性;仅更改数值而不更改规则不会生效。

下面的示例保存了五个演示文稿,所有公式、对齐方式和字体设置相同。前三个使用预设,后两个展示显式数值。

import com.aspose.slides.*;

class MathTextFactory {
    MathematicalText createText(String value) {
        MathematicalText text = new MathematicalText(value);
        text.getFormat().setFontHeight(24);
        text.getFormat().setLatinFont(new FontData("Cambria Math"));
        return text;
    }
}

MathTextFactory factory = new MathTextFactory();
int[] rules = { MathRowSpacingRule.SingleLineGap, MathRowSpacingRule.OneAndAHalfLineGap, MathRowSpacingRule.TwoLineGap, MathRowSpacingRule.Exactly, MathRowSpacingRule.Multiple };
int[] spacingValues = { 0, 0, 0, 20, 3 };
String[] ruleNames = { "SingleLineGap", "OneAndAHalfLineGap", "TwoLineGap", "Exactly", "Multiple" };

for (int i = 0; i < rules.length; i++) {
    String fileName = "equation-array-" + ruleNames[i] + ".pptx";
    Presentation presentation = new Presentation();
    try {
        IAutoShape mathShape = presentation.getSlides().get_Item(0).getShapes().addMathShape(20, 20, 600, 300);
        IParagraph paragraph = mathShape.getTextFrame().getParagraphs().get_Item(0);
        paragraph.getParagraphFormat().setSpaceBefore(0);
        paragraph.getParagraphFormat().setSpaceAfter(0);
        IMathParagraph mathParagraph = ((IMathPortion) paragraph.getPortions().get_Item(0)).getMathParagraph();
        mathParagraph.setJustification(MathJustification.LeftJustified);

        IMathElement[] rows = { factory.createText("x+y=3"), factory.createText("x-y=1"), factory.createText("x=2") };
        MathArray equationArray = new MathArray(rows[0]);
        equationArray.getArguments().add(rows[1]);
        equationArray.getArguments().add(rows[2]);
        equationArray.setBaseJustification(MathVerticalAlignment.Center);
        equationArray.setRowSpacingRule(rules[i]);
        equationArray.setRowSpacing(spacingValues[i]);
        MathematicalText leftText = factory.createText("A=");
        MathematicalText rightText = factory.createText("=B");
        IMathBlock equation = new MathBlock(leftText).join(equationArray).join(rightText);
        mathParagraph.add(equation);

        presentation.save(fileName, SaveFormat.Pptx);
    } finally {
        presentation.dispose();
    }
}

阵列行间距独立于段落间距。setSpaceBefore 与 setSpaceAfter 为包含段落的上下留白,而非阵列行之间的间距。同样,IMathParagraph.setJustification 水平定位整个数学段落,不会取代阵列的垂直对齐设置。

添加三角函数

当参数是当前元素且函数名已知时,使用 asArgumentOfFunction。

三角函数 cos 应用于 2x 的示意图

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 100);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathFunction cosine = new MathematicalText("2x")
            .asArgumentOfFunction(MathFunctionsOfOneArgument.Cos);

    mathParagraph.add(new MathBlock(cosine));

    presentation.save("trigonometric-function.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

添加下标和上标

使用下标和上标辅助方法处理索引和幂。当索引必须位于基数的左侧时,使用 setSubSuperscriptOnTheLeft。

左侧下标 1、上标 n 的大写字母 Y

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 100);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathLeftSubSuperscriptElement scripts = new MathematicalText("Y")
            .setSubSuperscriptOnTheLeft("1", "n");

    mathParagraph.add(new MathBlock(scripts));

    presentation.save("subscript-superscript.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

右侧下标和上标对齐

当两个脚本属于同一基数时,使用 MathRightSubSuperscriptElement。其 setAlignScripts 方法控制水平位置:false(默认)让它们沿基数轮廓排列,true 则水平对齐两个脚本。

此示例将同一可编辑表达式的两个副本并排放置。两者均使用数学斜体 f (U+1D453)、下标 1、上标 2,Cambria Math 字号 72 点。倾斜的基数使差异在 PowerPoint 中可见。运行示例前请先安装 Cambria Math。

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    presentation.getSlideSize().setSize(900, 250, SlideSizeScaleType.DoNotScale);
    ISlide slide = presentation.getSlides().get_Item(0);

    PortionFormat format = new PortionFormat();
    format.setFontHeight(72);
    format.setLatinFont(new FontData("Cambria Math"));

    for (int i = 0; i < 2; i++) {
        int left = 40 + i * 440;
        IAutoShape shape = slide.getShapes().addMathShape(left, 75, 380, 150);

        MathematicalText baseText = new MathematicalText("\uD835\uDC53", format);
        MathematicalText subscript = new MathematicalText("1", format);
        MathematicalText superscript = new MathematicalText("2", format);
        MathRightSubSuperscriptElement scripts = new MathRightSubSuperscriptElement(baseText, subscript, superscript);
        scripts.setAlignScripts(i == 1);

        MathPortion portion = (MathPortion) shape.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0);
        portion.getPortionFormat().setFontHeight(format.getFontHeight());
        portion.getPortionFormat().setLatinFont(format.getLatinFont());
        portion.getMathParagraph().add(new MathBlock(scripts));
    }

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

PowerPoint 中两组可编辑表达式,左侧 setAlignScripts 为 false,右侧为 true

左侧的下标起点比上标更左,遵循基数轮廓;右侧两脚本在水平上对齐。

添加分隔符

使用 enclose 将表达式包裹在分隔符之间。对于包含多个元素的分隔符表达式,还可以设置分隔字符。

包含 x、y、z 并用竖线分隔的分隔符表达式

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 100);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathDelimiter delimiter = new MathematicalText("x")
            .join("y")
            .join("z")
            .enclose('<', '>');
    delimiter.setSeparatorCharacter('|');

    mathParagraph.add(new MathBlock(delimiter));

    presentation.save("delimiters.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

分隔符的大小和对齐

将 true 传递给 setGrowToMatchOperandHeight 使括号在高操作数周围伸展,或传入 false 保持正常大小。使用 setDelimiterShape 并选择 MathDelimiterShape 中的两种值之一。Centered 将括号居中于数学轴(通过等号中线),Match 则与所包围的内容对齐。两种设置仅影响分隔符本身,内部表达式保持不变。

示例在 x 的指数位置放置分数,使表达式在基线之上延伸得更高。四个公式使用相同的括号和字体设置。

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);
    for (int row = 0; row < 2; row++) {
        for (int column = 0; column < 2; column++) {
            IMathFraction fraction = new MathematicalText("a + b").divide("c + d");
            IMathSuperscriptElement power = new MathematicalText("x").setSuperscript(fraction);
            IMathDelimiter delimiter = power.enclose('(', ')');
            delimiter.setGrowToMatchOperandHeight(row == 0);
            delimiter.setDelimiterShape(column == 0 ? MathDelimiterShape.Centered : MathDelimiterShape.Match);

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

在 PowerPoint 中比较两行可见伸展效果。上行的括号随指数伸展,左右形状相同;下行关闭伸展,左侧的较小括号(Centered)对齐等号,右侧的(Match)则在表达式上方更高。

PowerPoint 中四个公式,展示分隔符伸展开启和关闭的效果,左侧使用 Centered,右侧使用 Match

添加边框框

对分数调用 toBorderBox 可为整个表达式加框。返回的 IMathBorderBox 默认显示四条边。使用 setHideTop、setHideBottom、setHideLeft、setHideRight 可单独隐藏边线。

示例在一张幻灯片上放置相同分数的六个副本。为了显示取消效果,隐藏四条边并将 true 传给 setStrikethroughBottomLeftToTopRight 形成上升对角线 (↗),或传给 setStrikethroughTopLeftToBottomRight 形成下降对角线 (↘)。也可以使用 setStrikethroughHorizontal 或 setStrikethroughVertical 并组合任意可见边。

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    presentation.getSlideSize().setSize(540, 220, SlideSizeScaleType.DoNotScale);
    ISlide slide = presentation.getSlides().get_Item(0);

    class FractionBuilder {
        IMathBorderBox addFraction(float x, float y, boolean hideBorder) {
            IMathFraction fraction = new MathematicalText("x+1").divide("y+2");
            IMathBorderBox box = fraction.toBorderBox();
            box.setHideTop(hideBorder);
            box.setHideBottom(hideBorder);
            box.setHideLeft(hideBorder);
            box.setHideRight(hideBorder);

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

    FractionBuilder builder = new FractionBuilder();
    builder.addFraction(10, 10, false);

    IMathBorderBox partial = builder.addFraction(190, 10, false);
    partial.setHideTop(true);
    partial.setHideRight(true);

    builder.addFraction(370, 10, true).setStrikethroughBottomLeftToTopRight(true);
    builder.addFraction(10, 120, true).setStrikethroughTopLeftToBottomRight(true);
    builder.addFraction(190, 120, true).setStrikethroughHorizontal(true);
    builder.addFraction(370, 120, false).setStrikethroughVertical(true);

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

PowerPoint 中六个可编辑分数。上行:完整边框、下左边框、上升对角线。下行:下降对角线、水平划线、垂直划线并带完整边框

在此分数上,水平划线与分数线重叠。垂直划线穿过分子和分母,而外围边框仍然可见。这些线装饰整个表达式。普通文本的删除线只作用于文本运行中的字符。重新打开 PowerPoint 演示文稿后,仍可独立编辑分子和分母。

使用幻影元素控制可见性和布局

将表达式包装在 MathPhantom 中,可独立控制其可见性以及对公式布局的空间贡献。IMathPhantom 方法控制如下:

方法 效果
setShow 传入 false 隐藏表达式。除非下列方法接收 true,否则其尺寸仍会影响布局。
setZeroWidth 将表达式的水平宽度视为零,使相邻元素更靠近。
setZeroAsc 将其上升高度(基线以上的部分)视为零,可减少上方预留空间。
setZeroDesc 将其下降深度(基线以下的部分)视为零,可使分数线或其他内容更靠近下方邻近元素。

基线是普通数学字符所在的参考线。隐藏内容不会删除其尺寸,将尺寸设为零也不会删除表达式。底层表达式可通过 getBase 访问。调用 setShow 并传入 true 可再次显示,尺寸设置保持不变。

下面的示例创建了五种并排变体:一个可见分数、一个保留空间的隐藏分数,以及三个分别将宽度、上升或下降设为零的隐藏分数。每种变体使用相同的外围表达式和 Cambria Math,字号 24 点。所有公式形状的顶部位置相同,以灰色参考线标记。将幻影放在外部分数的分子中,可更直观地观察垂直布局变化。

import com.aspose.slides.*;
import java.awt.Color;

class MathTextFactory {
    MathematicalText createText(String value) {
        MathematicalText text = new MathematicalText(value);
        text.getFormat().setFontHeight(24);
        text.getFormat().setLatinFont(new FontData("Cambria Math"));
        return text;
    }
}

MathTextFactory factory = new MathTextFactory();
Presentation presentation = new Presentation();
try {
    presentation.getSlideSize().setSize(1000, 180, SlideSizeScaleType.DoNotScale);
    ISlide slide = presentation.getSlides().get_Item(0);

    String[] labels = { "Visible", "Hidden: reserves space", "Hidden: ZeroWidth", "Hidden: ZeroAsc", "Hidden: ZeroDesc" };

    IAutoShape guide = slide.getShapes().addAutoShape(ShapeType.Line, 10, 60, 980, 0);
    guide.getLineFormat().getFillFormat().setFillType(FillType.Solid);
    guide.getLineFormat().getFillFormat().getSolidFillColor().setColor(Color.LIGHT_GRAY);

    for (int i = 0; i < labels.length; i++) {
        int left = 10 + i * 200;

        IAutoShape label = slide.getShapes().addAutoShape(ShapeType.Rectangle, left, 10, 190, 30);
        label.getFillFormat().setFillType(FillType.NoFill);
        label.getLineFormat().getFillFormat().setFillType(FillType.NoFill);
        label.getTextFrame().setText(labels[i]);

        IPortionFormat labelFormat = label.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0).getPortionFormat();
        labelFormat.setFontHeight(14);
        labelFormat.getFillFormat().setFillType(FillType.Solid);
        labelFormat.getFillFormat().getSolidFillColor().setColor(Color.BLACK);

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

        MathematicalText leftText = factory.createText("x+");
        MathematicalText rightText = factory.createText("+y");
        IMathBlock numerator = new MathBlock(leftText).join(phantom).join(rightText);
        MathematicalText denominator = factory.createText("z");
        MathFraction equation = new MathFraction(numerator, denominator);

        IAutoShape shape = slide.getShapes().addMathShape(left, 60, 190, 100);
        shape.getTextFrame().getTextFrameFormat().setAnchoringType(TextAnchorType.Top);

        IMathPortion mathPortion = (IMathPortion) shape.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0);
        IMathParagraph mathParagraph = mathPortion.getMathParagraph();
        mathParagraph.add(new MathBlock(equation));
    }

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

PowerPoint 中的五个公式,对比可见分数、保留空间的隐藏分数以及 ZeroWidth、ZeroAsc、ZeroDesc 各自启用的隐藏分数

分组项

使用 group 在表达式上方或下方放置分组字符。可以添加极限以标记分组项。

表达式 x + y 分组,下方带有标签任意文本

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 120);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathLimit 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);
} finally {
    presentation.dispose();
}

格式化数学元素

仅在能提升公式可读性的情况下使用格式化辅助方法。例如,overbar 在数学元素上方添加横杠。

带有上横线的数学表达式 ABC

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);

    IAutoShape mathShape = slide.getShapes().addMathShape(20, 20, 700, 100);
    IMathParagraph mathParagraph = ((MathPortion) mathShape.getTextFrame().getParagraphs()
            .get_Item(0).getPortions().get_Item(0)).getMathParagraph();

    IMathBar overbar = new MathematicalText("ABC").overbar();

    mathParagraph.add(new MathBlock(overbar));

    presentation.save("overbar.pptx", SaveFormat.Pptx);
} finally {
    presentation.dispose();
}

在公式中使用符号字体

要在两个操作数之间插入 Wingdings 箭头,请为箭头创建单独的 MathematicalText 元素。对 MathematicalText.getFormat 返回的格式调用 setSymbolFont。这仅为箭头指定 Wingdings 字体,并保留两个操作数的原有格式。

字符代码和符号字体需一起选择。Wingdings 将 U+F0E0 显示为向右箭头。其他字体可能在同一代码点显示不同字形或根本没有字形。

import com.aspose.slides.*;

Presentation presentation = new Presentation();
try {
    ISlide slide = presentation.getSlides().get_Item(0);
    
    IAutoShape shape = slide.getShapes().addMathShape(20, 20, 240, 90);
    IMathPortion mathPortion = (IMathPortion) shape.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0);

    MathematicalText left = new MathematicalText("A");
    MathematicalText arrow = new MathematicalText("\uF0E0");
    MathematicalText right = new MathematicalText("B");
    arrow.getFormat().setSymbolFont(new FontData("Wingdings"));

    MathBlock 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 显示保存的公式如下。所有三个元素仍可编辑。

带有 Wingdings 向右箭头的可编辑公式,位于 A 与 B 之间

LoadOptions.setDefaultSymbolFont 在加载演示文稿时配置默认符号字体。为单个元素指定符号字体并不会将字体嵌入演示文稿。渲染环境中必须可用 Wingdings。

格式化已有公式中的文本

要在已有公式中格式化全文本,需要遍历每个数学块的元素树。IMathElement.getChildren 仅返回直接子节点,需递归调用以抵达分数、上下标、根式及其他嵌套结构内部的文本。检查当前元素及其子元素,以确保包括起始元素(当其为 MathematicalText 时)。

本示例假设 input.pptx 包含类似 z = xᵢ / ∛y 的公式,其中分数的分子含有下标,分母含有根式。仅处理块的顶层元素会遗漏分数内部的文本。示例在幻灯片文本框中查找数学段落,访问其块,通过 IMathPortion.getMathParagraph 获取,并使用 setFontHeight 将每个文本元素的字体大小设为 28 点(通过其 getFormat)。

import com.aspose.slides.*;

class MathTextFormatter {
    void formatMathText(IMathElement element) {
        if (element instanceof MathematicalText) {
            MathematicalText text = (MathematicalText) element;
            text.getFormat().setFontHeight(28);
        }

        for (IMathElement child : element.getChildren()) {
            formatMathText(child);
        }
    }
}

MathTextFormatter formatter = new MathTextFormatter();
Presentation presentation = new Presentation("input.pptx");
try {
    for (ISlide slide : presentation.getSlides()) {
        for (IShape shape : slide.getShapes()) {
            if (!(shape instanceof IAutoShape)) {
                continue;
            }

            IAutoShape autoShape = (IAutoShape) shape;
            if (autoShape.getTextFrame() == null) {
                continue;
            }

            for (IParagraph paragraph : autoShape.getTextFrame().getParagraphs()) {
                for (IPortion portion : paragraph.getPortions()) {
                    if (portion instanceof IMathPortion) {
                        IMathPortion mathPortion = (IMathPortion) portion;
                        for (IMathBlock block : mathPortion.getMathParagraph()) {
                            formatter.formatMathText(block);
                        }
                    }
                }
            }
        }
    }

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

保存的演示文稿在每个处理过的公式的所有层级中都更新了文本格式,同时保留了文本内容和数学结构。

快速参考

任务 主要 API
创建数学文本 MathematicalText
合并元素 IMathElement.join
创建分数 IMathElement.divide
添加上标或下标 setSuperscript, setSubscript
添加函数 function, asArgumentOfFunction
添加根式 IMathElement.radical
添加极限 setLowerLimit, setUpperLimit
添加左侧脚本 setSubSuperscriptOnTheLeft
添加求和和积分 nary, integral
添加矩阵 MathMatrix
添加公式阵列 toMathArray
添加分隔符 enclose
添加横线和边框 overbar, toBorderBox
分组项 group

常见问题

我可以编辑已有的 PowerPoint 公式吗?

可以。打开演示文稿,找到包含 MathPortion 的形状,调用 getMathParagraph,然后更新该段落中的数学块。

公式是否以可编辑的 PowerPoint 公式形式保存?

是的。保存为 PPTX 时,Aspose.Slides 会将公式写入可编辑的 Office 数学内容。

我能将公式导出为 LaTeX 吗?

可以。从其 IMathPortion 获取公式的 IMathParagraph,然后调用 IMathParagraph.toLatex 直接导出。完整示例请参阅 Export Math Equations from Presentations in Java。