在 Python 中將數學方程式加入 PowerPoint 簡報
概述
PowerPoint 將方程式儲存為 Office Math Markup Language (OMML)。使用 Aspose.Slides for Python via .NET,您可以以程式方式建立相同類型的數學內容:分數、根號、函數、極限、N 元運算子、矩陣、陣列以及格式化的數學區塊。
在 PowerPoint,使用者通常從 插入 > 方程式 加入方程式:

結果是投影片上可編輯的數學文字:

Aspose.Slides 透過三個主要物件建立此數學文字:
- 數學形狀,使用 add_math_shape 建立,是包含方程式的形狀。
- MathPortion 在形狀文字框內儲存數學內容。
- MathParagraph 包含一個或多個 MathBlock 物件。
以下大多數範例使用 MathematicalText 以及來自 MathElementBase 的流暢方法,以保持程式碼簡潔且易讀。
如需 MathML 匯出情境,請參閱 Export Math Equations from Presentations in Python via .NET。
建立方程式
此範例使用 add_math_shape 建立數學形狀,並加入畢氏定理:

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 120)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
equation = (
math.MathematicalText("c")
.set_superscript("2")
.join("=")
.join(math.MathematicalText("a").set_superscript("2"))
.join("+")
.join(math.MathematicalText("b").set_superscript("2"))
)
math_paragraph.add(equation)
presentation.save("pythagorean-theorem.pptx", slides.export.SaveFormat.PPTX)
結合數學區塊
當方程式的部份獨立以 MathBlock 物件建構時,使用 join_block 來結合它們。範例在左側區塊建立 c² =,在右側區塊建立 a² + b²。set_superscript 為所有三個次方建立可編輯的上標。
import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
shape = slide.shapes.add_math_shape(20, 20, 600, 100)
math_paragraph = shape.text_frame.paragraphs[0].portions[0].math_paragraph
left_block = math.MathBlock()
left_block.add(math.MathematicalText("c").set_superscript("2"))
left_block.add(math.MathematicalText("="))
right_block = math.MathBlock()
right_block.add(math.MathematicalText("a").set_superscript("2"))
right_block.add(math.MathematicalText("+"))
right_block.add(math.MathematicalText("b").set_superscript("2"))
combined_block = left_block.join_block(right_block)
math_paragraph.add(combined_block)
presentation.save("equation.pptx", slides.export.SaveFormat.PPTX)
join_block 回傳 left_block 本身,現在依序包含兩個部份,並使 right_block 為空。只需將合併後的區塊一次加入 MathParagraph。重新開啟 equation.pptx 後,段落只包含一個區塊,代表 c² = a² + b²,且三個次方均保留為數學上標。
若以 left_block.add(right_block) 呼叫 add,則嘗試將一個區塊直接嵌入另一個區塊,會拋出包住 .NET InvalidOperationException 的 RuntimeError。
加入分數
使用 divide 建立分數。您可以使用 MathFractionTypes 選擇分數樣式。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 100)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
fraction = math.MathematicalText("1").divide("x", math.MathFractionTypes.SKEWED)
math_paragraph.add(math.MathBlock(fraction))
presentation.save("fraction.pptx", slides.export.SaveFormat.PPTX)
對於堆疊式分數,使用 MathFractionTypes.BAR:
import aspose.slides.mathtext as math
stacked_fraction = math.MathematicalText("x + 1").divide("y - 1", math.MathFractionTypes.BAR)
加入根號
使用 radical 建立平方根、立方根或其他根。當前元素成為根號的底,參數則成為次方。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 100)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
radical = math.MathematicalText("x").radical("n")
math_paragraph.add(math.MathBlock(radical))
presentation.save("radical.pptx", slides.export.SaveFormat.PPTX)
顯示或隱藏平方根的次方
平方根可以顯示明確的 2,或使用傳統的 √x 記號。hide_degree 屬性於 MathRadical 控制顯示形式。兩種形式皆保留次方 2 與被開方的 x。

範例將相同的平方根儲存兩次。visible-degree.pptx 中的 2 為可見,hidden-degree.pptx 中的 2 為隱藏。
import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
radical = math.MathematicalText("x").radical("2")
shape = slide.shapes.add_math_shape(20, 20, 200, 100)
portion = shape.text_frame.paragraphs[0].portions[0]
portion.math_paragraph.add(math.MathBlock(radical))
radical.hide_degree = False
presentation.save("visible-degree.pptx", slides.export.SaveFormat.PPTX)
radical.hide_degree = True
presentation.save("hidden-degree.pptx", slides.export.SaveFormat.PPTX)
加入函數與極限
使用 as_argument_of_function 或 function 來建立 sin(x)、log(x) 等函數,或自訂函數名稱。對於極限,將 lim 放入 MathLimit 或使用 set_lower_limit。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 100)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
limit = (
math.MathematicalText("lim")
.set_lower_limit("x\u2192\u221E")
.function("x")
)
math_paragraph.add(math.MathBlock(limit))
presentation.save("functions-and-limits.pptx", slides.export.SaveFormat.PPTX)
若使用自訂函數名稱,先將函數名稱設為當前元素,然後以其參數呼叫 function:
import aspose.slides.mathtext as math
custom_function = math.MathematicalText("f").function("x + 1")
加入 N 元運算子與積分
使用 nary 來處理求和、聯集、交集及其他大型運算子。使用 integral 來處理積分。兩種方法皆可設定下限與上限。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 120)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
summation_base = (
math.MathematicalText("x")
.set_superscript("k")
.join(math.MathematicalText("a").set_superscript("n-k"))
)
summation = summation_base.nary(math.MathNaryOperatorTypes.SUMMATION, "k=0", "n")
math_paragraph.add(math.MathBlock(summation))
presentation.save("nary-operators.pptx", slides.export.SaveFormat.PPTX)
N 元運算子適用於可選下、上限的大型運算子。像 +、-、= 這類簡單運算子通常以 MathematicalText 加入,然後組合成表達式。
對於積分,使用 integral:
import aspose.slides.mathtext as math
integral_base = math.MathematicalText("x").join(math.MathematicalText("dx").to_box())
integral = integral_base.integral(math.MathIntegralTypes.SIMPLE, "0", "1")
建立複合運算子
若要將 == 為單一運算子放在兩個運算元之間,對包含兩個等號的 MathematicalText 呼叫 to_box。於產生的 MathBox 上,將 operator_emulator 設為 True,使其群組作為數學運算子。預設為 False。
no_break 控制方框內的換行。範例明確將其設定為預設值 True,以保持兩個等號在同一行。其餘部分仍可自動換行。
import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 300, 60)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
compound_operator = math.MathematicalText("==").to_box()
compound_operator.operator_emulator = True
compound_operator.no_break = True
equation = math.MathematicalText("a").join(compound_operator).join(math.MathematicalText("b"))
math_paragraph.add(equation)
presentation.save("compound-operator.pptx", slides.export.SaveFormat.PPTX)
加入矩陣
使用 MathMatrix 處理行與列。矩陣預設不包含括號,若需要括弧、方括號或大括號,請自行將矩陣包起來。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 120)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
matrix = math.MathMatrix(2, 3)
matrix[0, 0] = math.MathematicalText("1")
matrix[0, 1] = math.MathematicalText("x")
matrix[1, 0] = math.MathematicalText("x")
matrix[1, 1] = math.MathematicalText("2")
matrix[1, 2] = math.MathematicalText("y")
math_paragraph.add(math.MathBlock(matrix))
presentation.save("matrix.pptx", slides.export.SaveFormat.PPTX)
編輯現有矩陣
假設線性代數課程以 matrix.pptx 中的係數矩陣開始,該檔案由前述範例儲存。接下來的練習保留第一個方程式,將第二個方程式換成兩個新方程式,並調整變數集合。以 MathMatrix 取得現有矩陣,以保留仍適用的係數。

列與欄索引從 0 起算,且在每次呼叫時參照當時的矩陣狀態。於索引 1 前插入一列會將原本的第 2 列移至索引 2。於索引 2 後插入則會在最後附加一列。刪除第 2 列會移除原本的第 2 個方程式,並將附加的列上移一個位置。欄位亦以相同方式移位。
import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation("matrix.pptx") as presentation:
shape = presentation.slides[0].shapes[0]
portion = shape.text_frame.paragraphs[0].portions[0]
matrix = portion.math_paragraph[0][0]
matrix.insert_row_before(1)
matrix.insert_row_after(2)
matrix.delete_row(2)
matrix.insert_column_before(1)
matrix.insert_column_after(3)
matrix.delete_column(3)
matrix[1, 0] = math.MathematicalText("12")
matrix[1, 1] = math.MathematicalText("1")
matrix[2, 2] = math.MathematicalText("10")
matrix[2, 3] = math.MathematicalText("1")
for row in range(matrix.row_count):
for column in range(matrix.column_count):
if matrix[row, column] is None:
matrix[row, column] = math.MathematicalText("0")
matrix.set_column_alignment(0, math.MathHorizontalAlignment.LEFT)
matrix.set_columns_alignment(1, 3, math.MathHorizontalAlignment.RIGHT)
presentation.save("updated-matrix.pptx", slides.export.SaveFormat.PPTX)
set_column_alignment 將第一欄靠左對齊。set_columns_alignment 將從索引 1 起的連續三欄靠右對齊。在 updated-matrix.pptx 中,矩陣包含三個方程式與四個變數。原始第一列的係數 1 與 x 現在分別出現在第一與第三欄。

設定矩陣列與欄間距
範例開啟 fraction-matrix.pptx 中的 2 × 2 分數矩陣,並將最小欄寬設為 48 點、欄間距設為 12 點、列間距設為 1.5 行。
import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation("fraction-matrix.pptx") as presentation:
shape = presentation.slides[0].shapes[0]
portion = shape.text_frame.paragraphs[0].portions[0]
matrix = portion.math_paragraph[0][0]
matrix.min_column_width = 960
matrix.column_gap_rule = math.MathSpacingRules.EXACTLY
matrix.column_gap = 240
matrix.row_gap_rule = math.MathSpacingRules.MULTIPLE
matrix.row_gap = 3
presentation.save("matrix-spacing.pptx", slides.export.SaveFormat.PPTX)
min_column_width 設定每欄的最小寬度(單位為 twip,20 twip = 1 點)。column_gap 為相鄰欄位之間增加空間。兩者共同決定從一欄起始點到下一欄起始點的距離。
column_gap_rule 與 row_gap_rule 為每個方向選取 MathSpacingRules 的值。使用 EXACTLY 時,兩個間距值皆以 twip 為單位測量。使用 MULTIPLE 時,column_gap 的每單位代表 0.5 em,且 row_gap 的每單位代表半行。其他欄間距規則會忽略 column_gap。
這些設定僅套用於矩陣內部。段落間距則控制周圍文字的版面配置。若要設定方程式陣列內的列間距,請參閱 Configure Row Spacing。
加入方程式陣列
需要對齊方程式或垂直堆疊表達式時,使用 to_math_array。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 140)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
equation_array = (
math.MathematicalText("x")
.join("y")
.to_math_array()
)
math_paragraph.add(math.MathBlock(equation_array))
presentation.save("equation-array.pptx", slides.export.SaveFormat.PPTX)
對齊陣列與週圍元素
MathArray.base_justification 控制陣列相對於旁邊數學元素的垂直對齊。以下範例比較與第一列、陣列中心與最後一列對齊的差異。
以下範例建立三個相同的陣列,每個陣列都有三列,且鄰近元素為 A= 與 =B。所有數學文字使用 Cambria Math,字型大小 24 點。唯一變化的是陣列的對齊方式。
import aspose.slides as slides
import aspose.slides.mathtext as math
def create_text(value):
text = math.MathematicalText(value)
text.format.font_height = 24
text.format.latin_font = slides.FontData("Cambria Math")
return text
with slides.Presentation() as presentation:
presentation.slide_size.set_size(780, 200, slides.SlideSizeScaleType.DO_NOT_SCALE)
slide = presentation.slides[0]
alignments = [math.MathVerticalAlignment.TOP, math.MathVerticalAlignment.CENTER, math.MathVerticalAlignment.BOTTOM]
labels = ["Top", "Center", "Bottom"]
for i, alignment in enumerate(alignments):
label = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 20 + i * 260, 10, 240, 30)
label.fill_format.fill_type = slides.FillType.NO_FILL
label.line_format.fill_format.fill_type = slides.FillType.NO_FILL
label.text_frame.text = labels[i]
label_format = label.text_frame.paragraphs[0].portions[0].portion_format
label_format.font_height = 16
label_format.fill_format.fill_type = slides.FillType.SOLID
label_format.fill_format.solid_fill_color.color = slides.Color.black
math_shape = slide.shapes.add_math_shape(20 + i * 260, 60, 240, 130)
math_shape.text_frame.text_frame_format.anchoring_type = slides.TextAnchorType.TOP
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
math_paragraph.justification = math.MathJustification.LEFT_JUSTIFIED
rows = [create_text("x+y=3"), create_text("x-y=1"), create_text("x=2")]
equation_array = math.MathArray(rows)
equation_array.base_justification = alignment
left_text = create_text("A=")
right_text = create_text("=B")
equation = math.MathBlock(left_text).join(equation_array).join(right_text)
math_paragraph.add(equation)
presentation.save("equation-array-alignment.pptx", slides.export.SaveFormat.PPTX)
以下比較圖示在 PowerPoint 中儲存的簡報。請注意每個陣列旁邊的 A= 與 =B 位置。

設定列間距
row_spacing_rule 選取陣列內列的間距規則。row_spacing 提供明確間距規則的數值,預設規則會忽略此屬性。
若使用「精確」間距,數值以點為單位。若使用「比例」間距,數值以半行為單位:範例中的值 3 代表 1.5 行。指定明確值時,請同時設定兩個屬性;僅變更數值不會自動選取間距規則。
以下範例儲存五個簡報,方程式、對齊與字型設定相同。前三個使用預設規則,最後兩個則顯示明確數值。
import aspose.slides as slides
import aspose.slides.mathtext as math
def create_text(value):
text = math.MathematicalText(value)
text.format.font_height = 24
text.format.latin_font = slides.FontData("Cambria Math")
return text
settings = [
(math.MathRowSpacingRule.SINGLE_LINE_GAP, 0),
(math.MathRowSpacingRule.ONE_AND_A_HALF_LINE_GAP, 0),
(math.MathRowSpacingRule.TWO_LINE_GAP, 0),
(math.MathRowSpacingRule.EXACTLY, 20),
(math.MathRowSpacingRule.MULTIPLE, 3)
]
for rule, spacing in settings:
file_name = f"equation-array-{rule.name}.pptx"
with slides.Presentation() as presentation:
math_shape = presentation.slides[0].shapes.add_math_shape(20, 20, 600, 300)
paragraph = math_shape.text_frame.paragraphs[0]
paragraph.paragraph_format.space_before = 0
paragraph.paragraph_format.space_after = 0
math_paragraph = paragraph.portions[0].math_paragraph
math_paragraph.justification = math.MathJustification.LEFT_JUSTIFIED
rows = [create_text("x+y=3"), create_text("x-y=1"), create_text("x=2")]
equation_array = math.MathArray(rows)
equation_array.base_justification = math.MathVerticalAlignment.CENTER
equation_array.row_spacing_rule = rule
equation_array.row_spacing = spacing
left_text = create_text("A=")
right_text = create_text("=B")
equation = math.MathBlock(left_text).join(equation_array).join(right_text)
math_paragraph.add(equation)
presentation.save(file_name, slides.export.SaveFormat.PPTX)
陣列列間距與段落間距分開控制。space_before 與 space_after 為包含段落的上下空間,並不會影響陣列列之間的距離。同樣地,MathParagraph.justification 只會水平定位整個數學段落,而不會取代陣列的垂直對齊設定。
加入三角函數
當參數是當前元素且已知函數名稱時,使用 as_argument_of_function。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 100)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
cosine = math.MathematicalText("2x").as_argument_of_function(
math.MathFunctionsOfOneArgument.COS
)
math_paragraph.add(math.MathBlock(cosine))
presentation.save("trigonometric-function.pptx", slides.export.SaveFormat.PPTX)
加入下標與上標
使用下標與上標輔助函式處理指標與次方。若指標必須出現在基底的左側,請使用 set_sub_superscript_on_the_left。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 100)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
scripts = math.MathematicalText("Y").set_sub_superscript_on_the_left("1", "n")
math_paragraph.add(math.MathBlock(scripts))
presentation.save("subscript-superscript.pptx", slides.export.SaveFormat.PPTX)
對齊右側下標與上標
當兩個標註屬於同一基底時,使用 MathRightSubSuperscriptElement。其 align_scripts 屬性控制水平位置:False(預設)讓它們沿著基底輪廓排列,True 則使兩個標註水平對齊。
此範例將同一可編輯表達式的兩個副本並排放置。兩者皆使用數學斜體 f(U+1D453)、下標 1、上標 2,字型為 Cambria Math,大小 72 點。斜斜的基底使差異在 PowerPoint 中顯示清楚。執行範例前請先安裝 Cambria Math。
import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
presentation.slide_size.set_size(900, 250, slides.SlideSizeScaleType.DO_NOT_SCALE)
slide = presentation.slides[0]
text_format = slides.PortionFormat()
text_format.font_height = 72
text_format.latin_font = slides.FontData("Cambria Math")
for i in range(2):
left = 40 + i * 440
shape = slide.shapes.add_math_shape(left, 75, 380, 150)
base_text = math.MathematicalText("\U0001D453", text_format)
subscript = math.MathematicalText("1", text_format)
superscript = math.MathematicalText("2", text_format)
scripts = math.MathRightSubSuperscriptElement(base_text, subscript, superscript)
scripts.align_scripts = i == 1
portion = shape.text_frame.paragraphs[0].portions[0]
portion.portion_format.font_height = text_format.font_height
portion.portion_format.latin_font = text_format.latin_font
portion.math_paragraph.add(math.MathBlock(scripts))
presentation.save("aligned-scripts.pptx", slides.export.SaveFormat.PPTX)

左側的下標起始位置比上標更左,遵循基底輪廓。右側則兩個標註水平對齊。
加入分隔符
使用 enclose 將表達式包在分隔符內。亦可為包含多個元素的分隔符表達式設定分隔字元。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 100)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
delimiter = (
math.MathematicalText("x")
.join("y")
.join("z")
.enclose("<", ">")
)
delimiter.separator_character = "|"
math_paragraph.add(math.MathBlock(delimiter))
presentation.save("delimiters.pptx", slides.export.SaveFormat.PPTX)
大小與對齊分隔符
將 grow_to_match_operand_height 設為 True,讓括號隨較高的運算元伸展;設為 False 則保持原始大小。delimiter_shape 可接受兩種 MathDelimiterShape 之一。CENTERED 使括號在數學軸上置中(數學軸穿過等號中間),MATCH 則與所包內容對齊。兩者僅影響分隔符本身,內部表達式保持不變。
範例將分數放在 x 的指數上,使表達式在基線上方的延伸超過下方。四個方程式皆使用相同的括號與字型設定。
import aspose.slides as slides
import aspose.slides.mathtext as math
def add_expression(slide, left, top, grow, shape):
fraction = math.MathematicalText("a + b").divide("c + d")
power = math.MathematicalText("x").set_superscript(fraction)
delimiter = power.enclose("(", ")")
delimiter.grow_to_match_operand_height = grow
delimiter.delimiter_shape = shape
math_shape = slide.shapes.add_math_shape(left, top, 300, 100)
portion = math_shape.text_frame.paragraphs[0].portions[0]
portion.portion_format.font_height = 32
equation = math.MathematicalText("y = ").join(delimiter)
portion.math_paragraph.add(equation)
with slides.Presentation() as presentation:
slide = presentation.slides[0]
add_expression(slide, 20, 20, True, math.MathDelimiterShape.CENTERED)
add_expression(slide, 350, 20, True, math.MathDelimiterShape.MATCH)
add_expression(slide, 20, 140, False, math.MathDelimiterShape.CENTERED)
add_expression(slide, 350, 140, False, math.MathDelimiterShape.MATCH)
presentation.save("delimiter-sizing.pptx", slides.export.SaveFormat.PPTX)
在 PowerPoint 中比較各列可見成長效果。上列的括號會伸展以包住指數,且兩種形狀看起來相似。下列則關閉成長。左側較小的括號(CENTERED)與等號對齊,而右側(MATCH)則在表達式上方偏高。

加入框線盒
對分數呼叫 to_border_box,即可為整個表達式加上框線。回傳的 MathBorderBox 預設顯示四側。可使用 hide_top、hide_bottom、hide_left、hide_right 移除單獨的側邊。
範例在同一張投影片上放置六個相同的分數。為顯示取消效果,將四側全部隱藏,並設定 strikethrough_bottom_left_to_top_right 產生上升對角線 (↗) 或使用 strikethrough_top_left_to_bottom_right 產生下降對角線 (↘)。也可使用 strikethrough_horizontal 或 strikethrough_vertical,搭配任意可見側邊。
import aspose.slides as slides
import aspose.slides.mathtext as math
def add_fraction(slide, x, y, hide_border=False):
fraction = math.MathematicalText("x+1").divide("y+2")
box = fraction.to_border_box()
box.hide_top = box.hide_bottom = box.hide_left = box.hide_right = hide_border
shape = slide.shapes.add_math_shape(x, y, 160, 90)
portion = shape.text_frame.paragraphs[0].portions[0]
portion.portion_format.font_height = 28
portion.math_paragraph.add(math.MathBlock(box))
return box
with slides.Presentation() as presentation:
presentation.slide_size.set_size(540, 220, slides.SlideSizeScaleType.DO_NOT_SCALE)
slide = presentation.slides[0]
add_fraction(slide, 10, 10)
partial = add_fraction(slide, 190, 10)
partial.hide_top = True
partial.hide_right = True
add_fraction(slide, 370, 10, hide_border=True).strikethrough_bottom_left_to_top_right = True
add_fraction(slide, 10, 120, hide_border=True).strikethrough_top_left_to_bottom_right = True
add_fraction(slide, 190, 120, hide_border=True).strikethrough_horizontal = True
add_fraction(slide, 370, 120).strikethrough_vertical = True
presentation.save("border-box.pptx", slides.export.SaveFormat.PPTX)

在此分數上,水平刪除線會覆蓋分數線。垂直刪除線則穿過分子與分母,而周圍框線仍可見。這些線條裝飾整個表達式。普通文字的刪除線僅套用於文字執行區的字元。重新開啟 PowerPoint 簡報後,仍可獨立編輯分子與分母。
使用幽靈元素控制可見性與版面配置
將表達式包在 MathPhantom 中,可獨立控制其可見性與對方程式貢獻的空間。其屬性控制以下項目:
| Property | Effect |
|---|---|
| show | 設為 False 時隱藏表達式。其尺寸仍會影響版面配置,除非以下對應屬性為 True。 |
| zero_width | 將表達式的水平寬度視為 0,允許相鄰元素更靠近。 |
| zero_asc | 將其上升距(基線以上的高度)視為 0,可減少上方保留的空間。 |
| zero_desc | 將其下降距(基線以下的深度)視為 0,可使分數線或其他位於表達式下方的內容更靠近相鄰元素。 |
基線是普通數學字母所坐落的參考線。隱藏內容不會移除其尺寸,將尺寸視為 0 也不會刪除表達式。底層表達式仍可透過 base 取得。將 show 設回 True 後即可重新顯示;尺寸設定會保持不變。
下列範例建立五個並排變體:一個可見的分數、一個保留空間的隱藏分數,以及三個將單一維度設為 0 的隱藏分數。每個變體使用相同的周圍表達式與 Cambria Math(24 點)。所有方程式形狀的頂部位置相同,並以灰色參考線標示。將幽靈元素放在外層分數的分子中,可更容易觀察垂直版面變化。
import aspose.slides as slides
import aspose.slides.mathtext as math
def create_text(value):
text = math.MathematicalText(value)
text.format.font_height = 24
text.format.latin_font = slides.FontData("Cambria Math")
return text
with slides.Presentation() as presentation:
presentation.slide_size.set_size(1000, 180, slides.SlideSizeScaleType.DO_NOT_SCALE)
slide = presentation.slides[0]
labels = ["Visible", "Hidden: reserves space", "Hidden: ZeroWidth", "Hidden: ZeroAsc", "Hidden: ZeroDesc"]
guide = slide.shapes.add_auto_shape(slides.ShapeType.LINE, 10, 60, 980, 0)
guide.line_format.fill_format.fill_type = slides.FillType.SOLID
guide.line_format.fill_format.solid_fill_color.color = slides.Color.light_gray
for i, label_text in enumerate(labels):
left = 10 + i * 200
label = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, left, 10, 190, 30)
label.fill_format.fill_type = slides.FillType.NO_FILL
label.line_format.fill_format.fill_type = slides.FillType.NO_FILL
label.text_frame.text = label_text
label_format = label.text_frame.paragraphs[0].portions[0].portion_format
label_format.font_height = 14
label_format.fill_format.fill_type = slides.FillType.SOLID
label_format.fill_format.solid_fill_color.color = slides.Color.black
fraction_numerator = create_text("a+b")
fraction_denominator = create_text("c+d")
fraction = math.MathFraction(fraction_numerator, fraction_denominator)
phantom = math.MathPhantom(fraction)
phantom.show = i == 0
phantom.zero_width = i == 2
phantom.zero_asc = i == 3
phantom.zero_desc = i == 4
left_text = create_text("x+")
right_text = create_text("+y")
numerator = math.MathBlock(left_text).join(phantom).join(right_text)
denominator = create_text("z")
equation = math.MathFraction(numerator, denominator)
shape = slide.shapes.add_math_shape(left, 60, 190, 100)
shape.text_frame.text_frame_format.anchoring_type = slides.TextAnchorType.TOP
math_paragraph = shape.text_frame.paragraphs[0].portions[0].math_paragraph
math_paragraph.add(math.MathBlock(equation))
presentation.save("math-phantom.pptx", slides.export.SaveFormat.PPTX)

組合項目
使用 group 在表達式上方或下方放置分組字元。加入極限以為分組項目加上標籤。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 120)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
grouped = (
math.MathematicalText("x + y")
.group(chr(0x23DF), math.MathTopBotPositions.BOTTOM, math.MathTopBotPositions.TOP)
.set_lower_limit("any text")
)
math_paragraph.add(math.MathBlock(grouped))
presentation.save("grouped-terms.pptx", slides.export.SaveFormat.PPTX)
格式化數學元素
僅在能增進公式可讀性時使用格式化輔助函式。例如,使用 overbar 可在數學元素上方加上一條橫線。

import aspose.slides as slides
import aspose.slides.mathtext as math
with slides.Presentation() as presentation:
slide = presentation.slides[0]
math_shape = slide.shapes.add_math_shape(20, 20, 700, 100)
math_paragraph = math_shape.text_frame.paragraphs[0].portions[0].math_paragraph
overbar = math.MathematicalText("ABC").overbar()
math_paragraph.add(math.MathBlock(overbar))
presentation.save("overbar.pptx", slides.export.SaveFormat.PPTX)
格式化現有方程式中的文字
要在整個現有方程式中格式化文字,必須遍歷每個數學區塊的元素樹。MathElementBase.get_children 只會回傳直接子項目,需遞迴呼叫才能取得分數、上下標、根號及其他巢狀結構內的文字。除了檢查子項目,亦需檢查當前元素,以免漏掉本身為 MathematicalText 的情況。
此範例假設 input.pptx 中包含方程式,例如 z = xᵢ / ∛y,其中分數的分子含有下標、分母含有根號。僅處理區塊的頂層元素會遺漏分數內的文字。範例在投影片文字框中尋找數學區段,透過 MathPortion.math_paragraph 取得其區塊,並將每個文字元素的 format 屬性的 font_height 設為 28 點。
import aspose.slides as slides
import aspose.slides.mathtext as math
def format_math_text(element):
if isinstance(element, math.MathematicalText):
element.format.font_height = 28
for child in element.get_children():
format_math_text(child)
with slides.Presentation("input.pptx") as presentation:
for slide in presentation.slides:
for shape in slide.shapes:
if not isinstance(shape, slides.AutoShape) or shape.text_frame is None:
continue
for paragraph in shape.text_frame.paragraphs:
for portion in paragraph.portions:
if isinstance(portion, math.MathPortion):
for block in portion.math_paragraph:
format_math_text(block)
presentation.save("formatted-equations.pptx", slides.export.SaveFormat.PPTX)
儲存的簡報在每個已處理的方程式的所有層級中,都包含更新後的文字格式,同時保留文字內容與數學結構。
快速參考
| 任務 | 主要 API |
|---|---|
| 建立數學文字 | MathematicalText |
| 結合元素 | MathElementBase.join |
| 建立分數 | MathElementBase.divide |
| 加入上標或下標 | set_superscript, set_subscript |
| 加入函數 | function, as_argument_of_function |
| 加入根號 | radical |
| 加入極限 | set_lower_limit, set_upper_limit |
| 加入左側標註 | set_sub_superscript_on_the_left |
| 加入求和與積分 | nary, integral |
| 加入矩陣 | MathMatrix |
| 加入方程式陣列 | to_math_array |
| 加入分隔符 | enclose |
| 加入橫線與框線 | overbar, to_border_box |
| 組合項目 | group |
常見問答
我可以編輯現有的 PowerPoint 方程式嗎?
可以。開啟簡報,尋找包含 MathPortion 的形狀,取得其 math_paragraph,並更新該段落中的數學區塊。
方程式會儲存為可編輯的 PowerPoint 數學嗎?
會。將簡報儲存為 PPTX 時,Aspose.Slides 會將方程式寫入可編輯的 Office 數學內容。
我可以將方程式匯出為 LaTeX 嗎?
可以。從其 MathPortion 取得 MathParagraph,然後呼叫 MathParagraph.to_latex 直接匯出。完整範例請參閱 Export Math Equations from Presentations in Python via .NET。