在 Python 中管理 PowerPoint 文字段落

概觀

Aspose.Slides for Python via .NET 將文字表示為文字框、段落和部分的層級結構:

  • TextFrame 代表形狀中的文字容器,並提供其段落集合的存取。
  • Paragraph 代表文字框中的一個段落,提供其部分以及段落層級格式設定的存取。
  • Portion 代表段落內的文字執行。每個部分可以擁有其自己的文字與字元層級格式設定。

因此,一個段落可以透過使用多個部分,包含具有不同字型、顏色、大小和其他格式設定的文字。

建立與格式化段落

在形狀的文字框中建立段落,並使用部分來格式化個別的文字執行。本節說明如何在每個段落中結合多個部分,並套用不同的顏色、字型大小與樣式。

使用多個部分建立段落

以下 Python 範例建立三個段落,每個段落的 Paragraph.portions 集合中包含三個文字執行。它重複使用預設的段落與空的部分,然後加入其餘的段落與部分。透過 Portion.portion_format 套用格式:每個段落的第一個部分為紅色、粗體、15 點;第二個為藍色、斜體、18 點。第三個部分保留其預設格式:

import aspose.pydrawing as draw
import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 50, 150, 300, 150)
    text_frame = shape.text_frame

    first_paragraph = text_frame.paragraphs[0]
    first_paragraph.portions.add(slides.Portion())
    first_paragraph.portions.add(slides.Portion())

    second_paragraph = slides.Paragraph()
    second_paragraph.portions.add(slides.Portion())
    second_paragraph.portions.add(slides.Portion())
    second_paragraph.portions.add(slides.Portion())
    text_frame.paragraphs.add(second_paragraph)

    third_paragraph = slides.Paragraph()
    third_paragraph.portions.add(slides.Portion())
    third_paragraph.portions.add(slides.Portion())
    third_paragraph.portions.add(slides.Portion())
    text_frame.paragraphs.add(third_paragraph)

    for paragraph_index in range(text_frame.paragraphs.count):
        paragraph = text_frame.paragraphs[paragraph_index]
        for portion_index in range(paragraph.portions.count):
            portion = paragraph.portions[portion_index]
            portion.text = f"Portion {paragraph_index + 1}.{portion_index + 1}"

            if portion_index == 0:
                portion.portion_format.fill_format.fill_type = slides.FillType.SOLID
                portion.portion_format.fill_format.solid_fill_color.color = draw.Color.red
                portion.portion_format.font_bold = slides.NullableBool.TRUE
                portion.portion_format.font_height = 15
            elif portion_index == 1:
                portion.portion_format.fill_format.fill_type = slides.FillType.SOLID
                portion.portion_format.fill_format.solid_fill_color.color = draw.Color.blue
                portion.portion_format.font_italic = slides.NullableBool.TRUE
                portion.portion_format.font_height = 18

    presentation.save("paragraphs_with_portions.pptx", slides.export.SaveFormat.PPTX)

建立項目符號與編號清單

將段落文字組織成使用符號、編號或自訂圖片的清單。本節的範例涵蓋項目符號格式設定、多層清單,以及自訂起始編號。

建立項目符號或編號清單

項目符號與編號讓相關項目更易於掃描。在 Aspose.Slides 中,清單設定透過 BulletFormat 定義。

此 Python 範例在同一文字框中加入符號項目符號與編號項目。BulletFormat.type 用於選取項目符號類型,而 BulletFormat.char 提供符號, BulletFormat.numbered_bullet_style 則選擇編號樣式。兩個項目皆使用黑色項目符號,厚度為 100%,段落縮排為 25 點:

import aspose.pydrawing as draw
import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 200, 200, 400, 200)
    text_frame = shape.text_frame
    text_frame.paragraphs.clear()

    symbol_paragraph = slides.Paragraph()
    symbol_paragraph.text = "Welcome to Aspose.Slides"
    symbol_paragraph.paragraph_format.bullet.type = slides.BulletType.SYMBOL
    symbol_paragraph.paragraph_format.bullet.char = chr(0x2022)
    symbol_paragraph.paragraph_format.indent = 25
    symbol_paragraph.paragraph_format.bullet.color.color_type = slides.ColorType.RGB
    symbol_paragraph.paragraph_format.bullet.color.color = draw.Color.black
    symbol_paragraph.paragraph_format.bullet.is_bullet_hard_color = slides.NullableBool.TRUE
    symbol_paragraph.paragraph_format.bullet.height = 100
    text_frame.paragraphs.add(symbol_paragraph)

    numbered_paragraph = slides.Paragraph()
    numbered_paragraph.text = "This is a numbered item"
    numbered_paragraph.paragraph_format.bullet.type = slides.BulletType.NUMBERED
    numbered_paragraph.paragraph_format.bullet.numbered_bullet_style = slides.NumberedBulletStyle.BULLET_CIRCLE_NUM_WD_BLACK_PLAIN
    numbered_paragraph.paragraph_format.indent = 25
    numbered_paragraph.paragraph_format.bullet.color.color_type = slides.ColorType.RGB
    numbered_paragraph.paragraph_format.bullet.color.color = draw.Color.black
    numbered_paragraph.paragraph_format.bullet.is_bullet_hard_color = slides.NullableBool.TRUE
    numbered_paragraph.paragraph_format.bullet.height = 100
    text_frame.paragraphs.add(numbered_paragraph)

    presentation.save("bulleted_and_numbered_list.pptx", slides.export.SaveFormat.PPTX)

使用圖片項目符號

圖片項目符號讓您以自訂圖片取代符號或編號。

此範例需要工作目錄中有 bullets.png。此 Python 範例將圖像加入簡報的圖像集合作為 PPImage,並將其用作段落項目符號。它將 BulletFormat.type 設為使用圖片項目符號,並透過 BulletFormat.picture 指定圖像。BulletFormat.height 設為 100% 以相對段落文字調整項目符號大小:

import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    with slides.Images.from_file("bullets.png") as bullet_image:
        presentation_image = presentation.images.add_image(bullet_image)

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 200, 200, 400, 200)
    text_frame = shape.text_frame
    text_frame.paragraphs.clear()

    paragraph = slides.Paragraph()
    paragraph.text = "Welcome to Aspose.Slides"
    paragraph.paragraph_format.bullet.type = slides.BulletType.PICTURE
    paragraph.paragraph_format.bullet.picture.image = presentation_image
    paragraph.paragraph_format.bullet.height = 100
    text_frame.paragraphs.add(paragraph)

    presentation.save("picture_bullet.pptx", slides.export.SaveFormat.PPTX)
    presentation.save("picture_bullet.ppt", slides.export.SaveFormat.PPT)

建立多層清單

設定 ParagraphFormat.depth 以將段落放置於清單的不同層級。最高層的深度為 0。

此 Python 範例將 ParagraphFormat.depth 從 0 到 3 指派給四個段落,在同一文字框內建立層級結構。每個段落使用符號項目符號,透過 BulletFormat.char 在圓形項目符號與連字號間交替,以區分相鄰層級:

import aspose.pydrawing as draw
import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 200, 200, 400, 200)
    text_frame = shape.text_frame
    text_frame.paragraphs.clear()

    first_paragraph = slides.Paragraph()
    first_paragraph.text = "Content"
    first_paragraph.paragraph_format.bullet.type = slides.BulletType.SYMBOL
    first_paragraph.paragraph_format.bullet.char = chr(0x2022)
    first_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    first_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    first_paragraph.paragraph_format.depth = 0

    second_paragraph = slides.Paragraph()
    second_paragraph.text = "Second level"
    second_paragraph.paragraph_format.bullet.type = slides.BulletType.SYMBOL
    second_paragraph.paragraph_format.bullet.char = "-"
    second_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    second_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    second_paragraph.paragraph_format.depth = 1

    third_paragraph = slides.Paragraph()
    third_paragraph.text = "Third level"
    third_paragraph.paragraph_format.bullet.type = slides.BulletType.SYMBOL
    third_paragraph.paragraph_format.bullet.char = chr(0x2022)
    third_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    third_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    third_paragraph.paragraph_format.depth = 2

    fourth_paragraph = slides.Paragraph()
    fourth_paragraph.text = "Fourth level"
    fourth_paragraph.paragraph_format.bullet.type = slides.BulletType.SYMBOL
    fourth_paragraph.paragraph_format.bullet.char = "-"
    fourth_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    fourth_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    fourth_paragraph.paragraph_format.depth = 3

    text_frame.paragraphs.add(first_paragraph)
    text_frame.paragraphs.add(second_paragraph)
    text_frame.paragraphs.add(third_paragraph)
    text_frame.paragraphs.add(fourth_paragraph)

    presentation.save("multilevel_list.pptx", slides.export.SaveFormat.PPTX)

以自訂值開始編號清單項目

使用 BulletFormat.numbered_bullet_start_with 以設定編號段落的起始編號。

此 Python 範例將 BulletFormat.type 設為使用編號,並為三個段落分別指派 BulletFormat.numbered_bullet_start_with 為 2、3、7。每個段落的起始值分別設定,使顯示的編號可跳過數值:

import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 200, 200, 400, 200)
    text_frame = shape.text_frame
    text_frame.paragraphs.clear()

    first_paragraph = slides.Paragraph()
    first_paragraph.text = "Start at 2"
    first_paragraph.paragraph_format.bullet.type = slides.BulletType.NUMBERED
    first_paragraph.paragraph_format.bullet.numbered_bullet_start_with = 2
    text_frame.paragraphs.add(first_paragraph)

    second_paragraph = slides.Paragraph()
    second_paragraph.text = "Start at 3"
    second_paragraph.paragraph_format.bullet.type = slides.BulletType.NUMBERED
    second_paragraph.paragraph_format.bullet.numbered_bullet_start_with = 3
    text_frame.paragraphs.add(second_paragraph)

    third_paragraph = slides.Paragraph()
    third_paragraph.text = "Start at 7"
    third_paragraph.paragraph_format.bullet.type = slides.BulletType.NUMBERED
    third_paragraph.paragraph_format.bullet.numbered_bullet_start_with = 7
    text_frame.paragraphs.add(third_paragraph)

    presentation.save("custom_numbered_list.pptx", slides.export.SaveFormat.PPTX)

控制段落佈局與結束屬性

調整段落的邊距與縮排,以控制第一行與換行行的定位。您也可以將段落結束標記的格式與可見文字的部分分開設定。

設定首行縮排

使用 ParagraphFormat.indent 屬性控制段落的首行縮排。此屬性僅會移動第一行相對於段落左邊距的距離。正值會將第一行向右移動,而其餘行則保持與段落正文對齊。

當需要移動整個段落時,請使用 ParagraphFormat.margin_left。當只需要移動第一行時,請使用 ParagraphFormat.indent。

以下範例將三個段落的 ParagraphFormat.margin_left 設為 20 點,並將 ParagraphFormat.indent 設為 0、20、40 點。第一行的起始位置依次遞增,而換行行保持相同的左邊距:

import aspose.pydrawing as draw
import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 50, 50, 420, 220)
    shape.fill_format.fill_type = slides.FillType.NO_FILL
    shape.line_format.fill_format.fill_type = slides.FillType.SOLID
    shape.line_format.fill_format.solid_fill_color.color = draw.Color.gray

    text_frame = shape.text_frame
    text_frame.text_frame_format.autofit_type = slides.TextAutofitType.SHAPE
    text_frame.paragraphs.clear()

    first_paragraph = slides.Paragraph()
    first_paragraph.text = "No first-line indent. Wrapped lines start at the same position as the first line."
    first_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    first_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    first_paragraph.paragraph_format.margin_left = 20
    first_paragraph.paragraph_format.indent = 0

    second_paragraph = slides.Paragraph()
    second_paragraph.text = "First-line indent of 20 points. The first line moves to the right, while wrapped lines remain aligned to the paragraph body."
    second_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    second_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    second_paragraph.paragraph_format.margin_left = 20
    second_paragraph.paragraph_format.indent = 20

    third_paragraph = slides.Paragraph()
    third_paragraph.text = "First-line indent of 40 points. This paragraph shows a larger first-line offset to make the effect easier to see."
    third_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    third_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    third_paragraph.paragraph_format.margin_left = 20
    third_paragraph.paragraph_format.indent = 40

    text_frame.paragraphs.add(first_paragraph)
    text_frame.paragraphs.add(second_paragraph)
    text_frame.paragraphs.add(third_paragraph)

    presentation.save("paragraph_indent.pptx", slides.export.SaveFormat.PPTX)

結果:

段落的首行縮排

設定懸掛縮排

懸掛縮排是指段落布局中,第一行位於其餘行左側的情況。在 Aspose.Slides 中,您可透過 ParagraphFormat.indent 屬性建立此效果。將 indent 設為負值,即可將第一行相對於段落正文向左移動。

實務上,ParagraphFormat.margin_left 定義段落正文的左側位置,而 ParagraphFormat.indent 定義第一行相對於該邊距的位置。要建立懸掛縮排,請將正的 margin_left 與負的 indent 同時設定。

此格式特別適用於書目、參考文獻、詞彙表條目等需要換行行對齊於段落正文而非首行第一個字元的段落。

以下 Python 範例將 ParagraphFormat.margin_left 設為 40 與 60 點,並將 ParagraphFormat.indent 設為 -20 與 -30 點。每個段落的第一行皆位於換行行左側;第二個段落的懸掛縮排更深:

import aspose.pydrawing as draw
import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 50, 50, 420, 220)
    shape.fill_format.fill_type = slides.FillType.NO_FILL
    shape.line_format.fill_format.fill_type = slides.FillType.SOLID
    shape.line_format.fill_format.solid_fill_color.color = draw.Color.gray

    text_frame = shape.text_frame
    text_frame.text_frame_format.autofit_type = slides.TextAutofitType.SHAPE
    text_frame.paragraphs.clear()

    first_paragraph = slides.Paragraph()
    first_paragraph.text = "A hanging indent is created by combining a positive left margin with a negative indent. The first line starts to the left, while wrapped lines align with the paragraph body."
    first_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    first_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    first_paragraph.paragraph_format.margin_left = 40
    first_paragraph.paragraph_format.indent = -20

    second_paragraph = slides.Paragraph()
    second_paragraph.text = "This second example uses a deeper hanging indent so the difference between the first line and the wrapped lines is easier to compare."
    second_paragraph.paragraph_format.default_portion_format.fill_format.fill_type = slides.FillType.SOLID
    second_paragraph.paragraph_format.default_portion_format.fill_format.solid_fill_color.color = draw.Color.black
    second_paragraph.paragraph_format.margin_left = 60
    second_paragraph.paragraph_format.indent = -30

    text_frame.paragraphs.add(first_paragraph)
    text_frame.paragraphs.add(second_paragraph)

    presentation.save("hanging_indent.pptx", slides.export.SaveFormat.PPTX)

結果:

段落的懸掛縮排

設定段落結束執行屬性

Paragraph.end_paragraph_portion_format 屬性控制段落結束標記的格式。此範例載入必須至少包含一張投影片的 Test.pptx,並建立一個 PortionFormat ,將 PortionFormat.font_height 設為 48 點,將 PortionFormat.latin_font 設為 Times New Roman。然後將此格式指派給第二個段落的結束標記,保持可見文字的部分不變:

import aspose.slides as slides

with slides.Presentation("Test.pptx") as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 10, 10, 200, 250)
    text_frame = shape.text_frame
    text_frame.paragraphs.clear()

    first_paragraph = slides.Paragraph()
    first_paragraph.portions.add(slides.Portion("Sample text"))

    second_paragraph = slides.Paragraph()
    second_paragraph.portions.add(slides.Portion("Sample text 2"))

    end_paragraph_format = slides.PortionFormat()
    end_paragraph_format.font_height = 48
    end_paragraph_format.latin_font = slides.FontData("Times New Roman")
    second_paragraph.end_paragraph_portion_format = end_paragraph_format

    text_frame.paragraphs.add(first_paragraph)
    text_frame.paragraphs.add(second_paragraph)

    presentation.save("end_paragraph_format.pptx", slides.export.SaveFormat.PPTX)

計算已渲染的行數

有關影響自動換行與行末標點的段落規則,請參閱 Control Line Breaking 與 Control Hanging Punctuation。

使用 Paragraph.get_lines_count 可計算段落在文字佈局後佔用的行數,包含自動換行。這在檢查投影片範本的文字長度與佈局時很有用。

段落是 TextFrame.paragraphs 中的單一項目,可能佔用多行已渲染的行。一個明確的換行字元會在段落內強制換行,卻不會產生新段落。自動換行則根據可用寬度產生行,而不會在文字中插入明確的換行字元。因此,僅統計段落或換行字元無法得到已渲染的行數。

以下範例建立一個文字形狀,計算其行數,縮窄形狀後再以較短的字串取代文字。範例啟用 TextFrameFormat.wrap_text 並停用 TextFrameFormat.autofit_type,使形狀寬度控制換行,而不會自動縮小文字或調整形狀大小。每次測量皆使用 Paragraph.get_lines_count。形狀尺寸以點為單位。最後,範例再加入另一段落,並將整個文字框的行數相加。

import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 50, 50, 400, 200)
    text_frame = shape.text_frame
    text_frame.text_frame_format.wrap_text = slides.NullableBool.TRUE
    text_frame.text_frame_format.autofit_type = slides.TextAutofitType.NONE

    paragraph = text_frame.paragraphs[0]
    paragraph.paragraph_format.default_portion_format.font_height = 20
    paragraph.text = "This text demonstrates how automatic wrapping changes the number of rendered lines."
    print(f"Original width: {paragraph.get_lines_count()}")

    shape.width = 150
    print(f"Narrower shape: {paragraph.get_lines_count()}")

    paragraph.text = "Short text."
    print(f"Shorter text: {paragraph.get_lines_count()}")

    second_paragraph = slides.Paragraph()
    second_paragraph.text = "Another paragraph."
    second_paragraph.paragraph_format.default_portion_format.font_height = 20
    text_frame.paragraphs.add(second_paragraph)

    total_line_count = 0
    for current_paragraph in text_frame.paragraphs:
        total_line_count += current_paragraph.get_lines_count()
    print(f"Total lines in the text frame: {total_line_count}")

使用此文字與這些尺寸時,縮窄形狀會增加行數,而以短字串取代文字則會減少行數。精確的計數會因字型可用性與替代、字型大小、邊距、縮排、換行與自動適應設定而異;請在檢查範本時使用目標環境的字型與佈局設定。

僅靠行數無法判斷文字是否超出容器。可用的高度、行高、段落與行間距以及自動適應行為同樣重要;即使只有一行,當關閉換行時也可能超過可用寬度。

匯入與匯出段落內容

使用 HTML 可將文字帶入投影片,或將現有段落匯出供外部使用。本節同時說明如何將單一段落渲染為影像,包括表格儲存格中的段落。

將 HTML 文字匯入段落

使用 ParagraphCollection.add_from_html 將 HTML 標記轉換為文字框中的段落與部分。

此 Python 範例從工作目錄的 file.html 讀取 HTML,並將標記傳遞給 ParagraphCollection.add_from_html。它會清除文字框的預設段落,使框中僅保留匯入的內容。矩形形狀在投影片的每一側留有 10 點的邊距:

import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape_width = presentation.slide_size.size.width - 20
    shape_height = presentation.slide_size.size.height - 20
    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 10, 10, shape_width, shape_height)
    shape.fill_format.fill_type = slides.FillType.NO_FILL
    shape.text_frame.paragraphs.clear()

    with open("file.html", "r", encoding="utf-8") as html_stream:
        html = html_stream.read()

    shape.text_frame.paragraphs.add_from_html(html)
    presentation.save("html_text.pptx", slides.export.SaveFormat.PPTX)

將段落文字匯出為 HTML

使用 ParagraphCollection.export_to_html 匯出選取範圍的段落為 HTML。當在網站上重新使用投影片文字時,您可能希望保留本地強調效果,同時不帶入投影片的字型、大小或文字方塊樣式。將 TextToHtmlConversionOptions.text_inheritance_limit 設為適當的值,以控制匯出器在格式繼承上的深度。

下載 範例投影片 並放置於應用程式的工作目錄。其第一張投影片包含一個文字形狀,文字為「Inherited text; explicit red 18pt」。輸入特意使用了多層格式:

  • 投影片的預設文字樣式提供 Calibri 字型與 28 pt 大小。
  • 文字框的第一層文字樣式提供藍色文字與斜體。
  • 段落明確設定為粗體。
  • 第二個部分「explicit red 18pt」明確設定為紅色文字與 18 pt 大小。

以下完整範例將相同段落匯出三次。它將 TextToHtmlConversionOptions 傳給匯出方法,並將每個結果寫入獨立的 UTF-8 HTML 檔案:

import aspose.slides as slides

with slides.Presentation("text-inheritance.pptx") as presentation:
    text_shape = presentation.slides[0].shapes[0]
    paragraphs = text_shape.text_frame.paragraphs
    
    modes = {
        "All": slides.export.TextInheritanceLimit.ALL,
        "TextBox": slides.export.TextInheritanceLimit.TEXT_BOX,
        "ParagraphOnly": slides.export.TextInheritanceLimit.PARAGRAPH_ONLY,
    }

    for name, mode in modes.items():
        options = slides.export.TextToHtmlConversionOptions()
        options.text_inheritance_limit = mode

        html = paragraphs.export_to_html(0, paragraphs.count, options)
        with open(f"{name}.html", "w", encoding="utf-8") as html_stream:
            html_stream.write(html)

產生的 HTML 在第一個部分「Inherited text; 」中包含以下 CSS。表格列出相關宣告;其他產生的屬性為簡潔起見已省略。

輸出 第一個部分的相關 CSS 外觀
All.html font-family:'Calibri'; font-size:28pt; color:#0000ff; font-style:italic; font-weight:bold 藍色、粗體、斜體文字,字型為 Calibri、28 pt(若可用)。
TextBox.html color:#0000ff; font-style:italic; font-weight:bold 藍色、粗體、斜體文字;字型與大小由所在頁面或瀏覽器提供。
ParagraphOnly.html font-weight:bold 粗體文字;字型、大小、顏色與斜體樣式由所在頁面或瀏覽器提供。

第二個部分在所有三個輸出中皆保留 color:#ff0000、font-size:18pt 與 font-weight:bold。它在 ALL 與 TEXT_BOX 中亦保留斜體,但在 PARAGRAPH_ONLY 中不保留。限制繼承因此不會移除明確指派給段落或部分的格式。

在同一瀏覽器中開啟這些檔案以進行比較。在兩個受限制模式下,省略的 CSS 屬性將由目標頁面的樣式或瀏覽器預設值解析,最終外觀取決於 HTML 的使用環境。

將匯出的段落儲存為 UTF-8 HTML

TextToHtmlConversionOptions.encoding_name 會設定 ParagraphCollection.export_to_html 回傳之 HTML 字串的編碼宣告。當您儲存該字串時,Python open 的 encoding 參數決定文字寫入磁碟的方式。兩者皆使用 UTF-8,以便瀏覽器正確解碼多語言文字。

import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]
    
    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 0, 0, 400, 100)
    shape.text_frame.text = "Café | Ωω | 日本語 | 😀"

    options = slides.export.TextToHtmlConversionOptions()
    options.encoding_name = "utf-8"
    options.add_clipboard_fragment_header = False

    paragraphs = shape.text_frame.paragraphs
    html = paragraphs.export_to_html(0, paragraphs.count, options)
    with open("paragraphs.html", "w", encoding="utf-8") as html_stream:
        html_stream.write(html)

儲存的檔案宣告 charset=utf-8,且內容為 UTF-8 位元組。在瀏覽器中開啟 paragraphs.html 可保留文字 “Café | Ωω | 日本語 | 😀”。

產生 HTML 剪貼簿片段

ParagraphCollection.export_to_html 會回傳 HTML 字串。將 TextToHtmlConversionOptions.add_clipboard_fragment_header 設為 False 可取得普通 HTML,設為 True 則會包含 Windows 剪貼簿標頭。此標頭提供環繞 HTML 的 UTF-8 位元組偏移(StartHTML 與 EndHTML)以及要貼上的片段偏移(StartFragment 與 EndFragment)。

此範例將兩個格式化段落分別匯出為普通 HTML(html)與 HTML 剪貼簿片段(clipboard_html)。將片段寫入系統剪貼簿是另一個應用步驟。若剪貼簿 API 期待原始位元組,請以 UTF-8(不含 BOM)編碼片段。

import aspose.slides as slides

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    shape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 0, 0, 400, 100)
    paragraphs = shape.text_frame.paragraphs
    paragraphs.clear()
    paragraphs.add_from_html("<p>Status: <b>Ready</b></p><p><i>Next steps</i></p>")

    options = slides.export.TextToHtmlConversionOptions()
    options.add_clipboard_fragment_header = False
    html = paragraphs.export_to_html(0, paragraphs.count, options)

    options.add_clipboard_fragment_header = True
    clipboard_html = paragraphs.export_to_html(0, paragraphs.count, options)

將段落渲染為影像

Paragraph.get_image 直接渲染單一段落,回傳 IImage。使用 IImage.save 可將結果儲存至檔案或串流。您不需要渲染包含的形狀或手動裁切位圖。

若段落無法在其父集合中找到、沒有有效的渲染範圍,或無法渲染,則 Paragraph.get_image 可能回傳 None。在儲存之前請檢查結果,並在使用完畢後釋放返回的影像。

以預設比例渲染段落

此範例使用 sample.pptx,該投影片僅有一張投影片,第一個形狀為包含三個段落的文字方塊。

包含三個段落的文字方塊

以下範例選取索引為 1 的第二段落,呼叫不帶比例參數的 Paragraph.get_image。它會先檢查形狀是否包含所需段落,且渲染返回影像後才呼叫 IImage.save 以 PNG 格式儲存。使用上下文管理器在使用完畢後釋放影像資源。

import aspose.slides as slides

with slides.Presentation("sample.pptx") as presentation:
    shape = presentation.slides[0].shapes[0]

    if isinstance(shape, slides.AutoShape) and shape.text_frame is not None and shape.text_frame.paragraphs.count > 1:
        paragraph = shape.text_frame.paragraphs[1]
        paragraph_image = paragraph.get_image()

        if paragraph_image is not None:
            with paragraph_image:
                paragraph_image.save("paragraph.png", slides.ImageFormat.PNG)
        else:
            print("The paragraph could not be rendered.")
    else:
        print("The expected text shape or paragraph was not found.")

結果:

段落影像

在表格儲存格中以縮放比例渲染段落

使用接受 scale_x 與 scale_y 參數的 Paragraph.get_image 重載,以設定水平與垂直縮放係數。以下範例建立表格,在第一個儲存格中以兩倍寬度與高度渲染段落,並將結果儲存為 PNG 影像。

import aspose.slides as slides

scale_x = 2
scale_y = 2

with slides.Presentation() as presentation:
    slide = presentation.slides[0]

    table = slide.shapes.add_table(50, 50, [300], [80])
    paragraph = table.rows[0][0].text_frame.paragraphs[0]
    paragraph.text = "Text in a table cell"

    paragraph_image = paragraph.get_image(scale_x, scale_y)
    if paragraph_image is not None:
        with paragraph_image:
            paragraph_image.save("table_paragraph.png", slides.ImageFormat.PNG)
    else:
        print("The paragraph could not be rendered.")

縮放係數 1 代表該軸保持預設像素大小。例如,兩個係數皆為 2 時,影像的寬度與高度大約為預設尺寸的兩倍,像素總數約為四倍。較大的係數通常可在縮放或高解析度輸出時產生更銳利的文字,但也會增加記憶體使用量與檔案大小。小於 1 的係數會產生較小且細節較少的影像。使用相同的係數可保留段落的長寬比例;不同的水平與垂直係數則會分別拉伸輸出。

在需要包含形狀填充、邊框或其他視覺上下文時,使用 Shape.get_image 渲染整個形狀仍然很有用。若僅需段落影像,請使用 Paragraph.get_image。

常見問題集

我可以完全停用文字框內的換行嗎?

可以。將 TextFrameFormat.wrap_text 設為停用,即可禁止換行,使行不會在文字框邊緣斷開。

我要如何取得特定段落在投影片上的精確邊界?

使用 Paragraph.get_rect 取得段落的外框矩形。Portion.get_rect 則提供單一部分的邊界。

段落的對齊方式(左、右、置中或兩端對齊)在何處控制?

ParagraphFormat.alignment 為段落層級設定,會套用於整個段落,不受單一部分格式影響。

如需在每行內依不同字型大小垂直對齊部分,請參閱 Align Fonts Within a Line。

我可以為段落的一部分設定校對語言嗎?

可以。將 PortionFormat.language_id 設定於個別部分,即可讓同一段落包含多種語言的文字。