在 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();
}

合併 Math Block

當方程式的部份以 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²,且三個次方皆保留為數學上標。

若以 leftBlock.add(rightBlock) 呼叫 add,會嘗試直接將一個區塊巢入另一個區塊,進而拋出 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 建立平方根、立方根或其他根號。當前元素成為底數,參數成為指數。

含有 x 的 n 次根號表達式

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 中 2 可見,hidden-degree.pptx 中 2 隱藏。

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();
}

顯示或隱藏空矩陣格的佔位符

預設情況下,IMathMatrix.getHidePlaceholders 會回傳 false。PowerPoint 在編輯投影片時會在每個空格顯示虛點框。呼叫 setHidePlaceholders 並傳入 true,即可隱藏這些框。

以下範例將兩個 2×2 矩陣並排放置。每個矩陣的對角線上分別為 a 與 b,其餘兩格為 null。

import com.aspose.slides.*;

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

    for (boolean hide : new boolean[] { false, true }) {
        IMathMatrix matrix = new MathMatrix(2, 2);
        matrix.set_Item(0, 0, new MathematicalText("a"));
        matrix.set_Item(1, 1, new MathematicalText("b"));
        matrix.setHidePlaceholders(hide);

        IAutoShape shape = slide.getShapes().addMathShape(hide ? 360 : 80, 150, 220, 120);
        IMathPortion portion = (IMathPortion) 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();
}

在 PowerPoint 的「普通檢視」中開啟 matrix-placeholders.pptx。點擊任一方程式以編輯,然後點擊投影片空白區比較兩個矩陣。

setHidePlaceholders(false) setHidePlaceholders(true)
PowerPoint 在兩個空格中顯示虛點框。 PowerPoint 只顯示對角線上的 a 與 b。

隱藏佔位符可保持每列每行的完整性。兩個矩陣仍為 2×2,空格仍為 null,不會被填入零值。虛點框只是 PowerPoint 的編輯指示。

編輯現有矩陣

假設在 matrix.pptx 中已有線性代數課程的係數矩陣(由前述範例建立)。接下來的練習要保留第一個方程式,將第二個方程式換成兩個新方程式,並調整變數集合。請透過 IMathMatrix 開啟已存在的矩陣,以保留仍適用的係數。

原始兩列係數矩陣,第一列為 1、x 與空格,第二列為 x、2、y

行與列索引從 0 起算,指向當前狀態的矩陣。於索引 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。

大寫 Y,左側下標 1、上標 n 的示意圖

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,字型大小 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();
}

兩個可編輯表達式,左側 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。上列:完整邊框、底部與左側、上升對角線。下列:下降對角線、水平刪除線、垂直刪除線加完整邊框。

在此分數上,水平刪除線會與分數線重疊。垂直刪除線會貫穿分子與分母,且外框仍保持可見。這些線條裝飾整個表達式。一般文字的刪除線僅作用於文字跑。重新開啟簡報後,仍可分別編輯分子與分母。

使用幻影元素控制可見度與版面配置

將表達式包裹於 MathPhantom,可獨立控制其可見度與對方程式所貢獻的空間。IMathPhantom 的方法控制以下行為:

方法 效果
setShow 傳入 false 隱藏表達式。除非以下方法傳入 true,否則其尺寸仍會影響版面配置。
setZeroWidth 將表達式的水平寬度視為 0,讓相鄰元素更靠近。
setZeroAsc 將其上升高度(基線以上)視為 0,可減少鄰近元素上方的預留空間。
setZeroDesc 將其下降深度(基線以下)視為 0,可使分數線或其他內容更貼近下方元素。

基線是普通數學字母所排列的參考線。隱藏內容並不會移除其尺寸,將尺寸視為零亦不會刪除表達式。底層表達式仍可透過 getBase 取得。傳入 true 給 setShow 可再次顯示,且先前的尺寸設定仍會保留。

下面的範例建立五個並排的變體:一個可見分數、一個保留空間的隱藏分數,以及三個將單一維度視為零的隱藏分數。每個變體皆使用相同的周圍表達式與 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 以標籤「any text」置於下方的群組表示式

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 會如下顯示已保存的方程式。三個元素皆仍可編輯。

在 A 與 B 之間帶有 Wingdings 右箭頭的可編輯方程式

LoadOptions.setDefaultSymbolFont 可在載入簡報時設定預設符號字型。為單一元素指定符號字型不會將字型嵌入簡報。Wingdings 必須在渲染環境中可用。

格式化現有方程式中的文字

若要格式化現有方程式內的文字,請遍歷每個數學區塊的元素樹。IMathElement.getChildren 只會返回直接子項目,需遞迴呼叫以取得分數、上下標、根號等巢狀結構內的文字。亦須檢查當前元素本身,以包含起始元素為 MathematicalText 時的情況。

此範例假設 input.pptx 包含方程式,例如 z = xᵢ / ∛y,其中分數的分子帶有下標,分母為根號。僅處理區塊的頂層元素會遺漏分數內的文字。範例在投影片文字框中尋找數學部分,透過 IMathPortion.getMathParagraph 取得其區塊,並使用 setFontHeight 於每個文字元素的 getFormat 方法將字型大小設定為 28 點。

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。