Quản lý các đoạn văn bản PowerPoint trong Python qua Java

Tổng quan

Aspose.Slides for Python via Java biểu diễn văn bản dưới dạng một hệ thống phân cấp các khung văn bản, đoạn và phần:

  • TextFrame đại diện cho vùng chứa văn bản trong một hình dạng và cung cấp quyền truy cập vào bộ sưu tập đoạn của nó.
  • Paragraph đại diện cho một đoạn trong một khung văn bản và cung cấp quyền truy cập vào các phần và định dạng ở mức đoạn.
  • Portion đại diện cho một đoạn văn bản trong một đoạn. Mỗi phần có thể có văn bản và định dạng ký tự riêng.

Do đó một đoạn có thể chứa văn bản với các phông chữ, màu sắc, kích thước và các định dạng khác nhau bằng cách sử dụng nhiều phần.

Tạo và Định dạng Đoạn

Tạo Đoạn với Nhiều Phần

Các bước sau tạo một khung văn bản có ba đoạn, mỗi đoạn chứa ba phần:

  1. Tạo một thể hiện của lớp Presentation.
  2. Truy cập slide liên quan qua chỉ mục của nó.
  3. Thêm một AutoShape hình chữ nhật vào slide.
  4. Truy cập TextFrame của hình dạng.
  5. Sử dụng đoạn mặc định và thêm hai đối tượng Paragraph nữa vào khung văn bản.
  6. Thêm đủ các đối tượng Portion để mỗi đoạn chứa ba phần. Đoạn mặc định đã chứa một phần trống.
  7. Đặt văn bản cho mỗi phần.
  8. Áp dụng định dạng ký tự qua Portion.getPortionFormat.
  9. Lưu bản trình bày đã sửa đổi.

Ví dụ Python này thực hiện các bước trên:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import FillType, NullableBool, Paragraph, Portion, Presentation, SaveFormat, ShapeType
from java.awt import Color

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 50, 150, 300, 150)
    text_frame = shape.getTextFrame()
    first_paragraph = text_frame.getParagraphs().get_Item(0)
    first_paragraph.getPortions().add(Portion())
    first_paragraph.getPortions().add(Portion())
    second_paragraph = Paragraph()
    second_paragraph.getPortions().add(Portion())
    second_paragraph.getPortions().add(Portion())
    second_paragraph.getPortions().add(Portion())
    text_frame.getParagraphs().add(second_paragraph)
    third_paragraph = Paragraph()
    third_paragraph.getPortions().add(Portion())
    third_paragraph.getPortions().add(Portion())
    third_paragraph.getPortions().add(Portion())
    text_frame.getParagraphs().add(third_paragraph)
    paragraph_count = text_frame.getParagraphs().getCount()
    for paragraph_index in range(paragraph_count):
        paragraph = text_frame.getParagraphs().get_Item(paragraph_index)
        portion_count = paragraph.getPortions().getCount()
        for portion_index in range(portion_count):
            portion = paragraph.getPortions().get_Item(portion_index)
            portion.setText(f"Portion {paragraph_index + 1}.{portion_index + 1}")
            if portion_index == 0:
                portion.getPortionFormat().getFillFormat().setFillType(FillType.Solid)
                portion.getPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.RED)
                portion.getPortionFormat().setFontBold(NullableBool.True_)
                portion.getPortionFormat().setFontHeight(15)
            elif portion_index == 1:
                portion.getPortionFormat().getFillFormat().setFillType(FillType.Solid)
                portion.getPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLUE)
                portion.getPortionFormat().setFontItalic(NullableBool.True_)
                portion.getPortionFormat().setFontHeight(18)
    presentation.save("paragraphs_with_portions.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

Tạo Danh sách Đánh dấu và Đánh số

Tạo Danh sách Đánh dấu hoặc Đánh số

Các dấu đầu dòng và số giúp người đọc dễ quét các mục liên quan hơn. Trong Aspose.Slides, cài đặt danh sách được xác định qua BulletFormat.

  1. Tạo một thể hiện của lớp Presentation.
  2. Truy cập slide liên quan qua chỉ mục của nó.
  3. Thêm một AutoShape vào slide đã chọn.
  4. Truy cập TextFrame của hình dạng.
  5. Xóa đoạn mặc định khỏi khung văn bản.
  6. Tạo một Paragraph cho dấu đầu dòng ký hiệu.
  7. Đặt BulletFormat.setType thành BulletType.Symbol và chỉ định ký tự dấu đầu dòng.
  8. Đặt văn bản đoạn, thụt lề, màu dấu đầu dòng và độ cao dấu đầu dòng.
  9. Thêm đoạn vào khung văn bản.
  10. Tạo một đoạn thứ hai và đặt BulletFormat.setType thành BulletType.Numbered.
  11. Cấu hình kiểu dấu đầu dòng có số và thêm đoạn vào khung văn bản.
  12. Lưu bản trình bày.

Ví dụ Python này tạo một dấu đầu dòng ký hiệu và một dấu đầu dòng có số:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import BulletType, ColorType, NullableBool, NumberedBulletStyle, Paragraph, Presentation, SaveFormat, ShapeType
from java.awt import Color

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 200, 200, 400, 200)
    text_frame = shape.getTextFrame()
    text_frame.getParagraphs().clear()
    symbol_paragraph = Paragraph()
    symbol_paragraph.setText("Welcome to Aspose.Slides")
    symbol_paragraph.getParagraphFormat().getBullet().setType(BulletType.Symbol)
    symbol_paragraph.getParagraphFormat().getBullet().setChar("•")
    symbol_paragraph.getParagraphFormat().setIndent(25)
    symbol_paragraph.getParagraphFormat().getBullet().getColor().setColorType(ColorType.RGB)
    symbol_paragraph.getParagraphFormat().getBullet().getColor().setColor(Color.BLACK)
    symbol_paragraph.getParagraphFormat().getBullet().setBulletHardColor(NullableBool.True_)
    symbol_paragraph.getParagraphFormat().getBullet().setHeight(100)
    text_frame.getParagraphs().add(symbol_paragraph)
    numbered_paragraph = Paragraph()
    numbered_paragraph.setText("This is a numbered item")
    numbered_paragraph.getParagraphFormat().getBullet().setType(BulletType.Numbered)
    numbered_paragraph.getParagraphFormat().getBullet().setNumberedBulletStyle(NumberedBulletStyle.BulletCircleNumWDBlackPlain)
    numbered_paragraph.getParagraphFormat().setIndent(25)
    numbered_paragraph.getParagraphFormat().getBullet().getColor().setColorType(ColorType.RGB)
    numbered_paragraph.getParagraphFormat().getBullet().getColor().setColor(Color.BLACK)
    numbered_paragraph.getParagraphFormat().getBullet().setBulletHardColor(NullableBool.True_)
    numbered_paragraph.getParagraphFormat().getBullet().setHeight(100)
    text_frame.getParagraphs().add(numbered_paragraph)
    presentation.save("bulleted_and_numbered_list.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

Sử dụng Dấu đầu dòng Hình ảnh

Dấu đầu dòng hình ảnh cho phép bạn sử dụng một hình ảnh tùy chỉnh thay cho ký hiệu hoặc số.

  1. Tạo một thể hiện của lớp Presentation.
  2. Truy cập slide liên quan qua chỉ mục của nó.
  3. Thêm một AutoShape và truy cập TextFrame của nó.
  4. Xóa đoạn mặc định khỏi khung văn bản.
  5. Tải hình ảnh dấu đầu dòng và thêm nó vào bộ sưu tập hình ảnh của bản trình bày dưới dạng một PPImage.
  6. Tạo một Paragraph và đặt văn bản cho nó.
  7. Đặt BulletFormat.setType thành BulletType.Picture.
  8. Gán hình ảnh qua BulletFormat.getPicture và đặt độ cao dấu đầu dòng.
  9. Thêm đoạn vào khung văn bản.
  10. Lưu bản trình bày đã sửa đổi.

Ví dụ Python này tạo một dấu đầu dòng hình ảnh:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import BulletType, Images, Paragraph, Presentation, SaveFormat, ShapeType

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    bullet_image = Images.fromFile("bullets.png")
    try:
        presentation_image = presentation.getImages().addImage(bullet_image)
    finally:
        bullet_image.dispose()
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 200, 200, 400, 200)
    text_frame = shape.getTextFrame()
    text_frame.getParagraphs().clear()
    paragraph = Paragraph()
    paragraph.setText("Welcome to Aspose.Slides")
    paragraph.getParagraphFormat().getBullet().setType(BulletType.Picture)
    paragraph.getParagraphFormat().getBullet().getPicture().setImage(presentation_image)
    paragraph.getParagraphFormat().getBullet().setHeight(100)
    text_frame.getParagraphs().add(paragraph)
    presentation.save("picture_bullet.pptx", SaveFormat.Pptx)
    presentation.save("picture_bullet.ppt", SaveFormat.Ppt)
finally:
    presentation.dispose()

Tạo Danh sách Đa cấp

Đặt ParagraphFormat.setDepth để đặt các đoạn ở các cấp độ khác nhau của danh sách. Cấp độ trên cùng có độ sâu 0.

  1. Tạo một Presentation và truy cập một slide.
  2. Thêm một AutoShape và xóa đoạn mặc định khỏi khung văn bản của nó.
  3. Tạo bốn đoạn và cấu hình các ký hiệu dấu đầu dòng của chúng.
  4. Đặt giá trị ParagraphFormat.setDepth cho chúng là 0, 1, 2 và 3.
  5. Thêm các đoạn vào khung văn bản và lưu bản trình bày.

Ví dụ Python này tạo một danh sách đánh dấu bốn cấp:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import BulletType, FillType, Paragraph, Presentation, SaveFormat, ShapeType
from java.awt import Color

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 200, 200, 400, 200)
    text_frame = shape.getTextFrame()
    text_frame.getParagraphs().clear()
    first_paragraph = Paragraph()
    first_paragraph.setText("Content")
    first_paragraph.getParagraphFormat().getBullet().setType(BulletType.Symbol)
    first_paragraph.getParagraphFormat().getBullet().setChar("•")
    first_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    first_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    first_paragraph.getParagraphFormat().setDepth(0)
    second_paragraph = Paragraph()
    second_paragraph.setText("Second level")
    second_paragraph.getParagraphFormat().getBullet().setType(BulletType.Symbol)
    second_paragraph.getParagraphFormat().getBullet().setChar('-')
    second_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    second_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    second_paragraph.getParagraphFormat().setDepth(1)
    third_paragraph = Paragraph()
    third_paragraph.setText("Third level")
    third_paragraph.getParagraphFormat().getBullet().setType(BulletType.Symbol)
    third_paragraph.getParagraphFormat().getBullet().setChar("•")
    third_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    third_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    third_paragraph.getParagraphFormat().setDepth(2)
    fourth_paragraph = Paragraph()
    fourth_paragraph.setText("Fourth level")
    fourth_paragraph.getParagraphFormat().getBullet().setType(BulletType.Symbol)
    fourth_paragraph.getParagraphFormat().getBullet().setChar('-')
    fourth_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    fourth_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    fourth_paragraph.getParagraphFormat().setDepth(3)
    text_frame.getParagraphs().add(first_paragraph)
    text_frame.getParagraphs().add(second_paragraph)
    text_frame.getParagraphs().add(third_paragraph)
    text_frame.getParagraphs().add(fourth_paragraph)
    presentation.save("multilevel_list.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

Bắt đầu Các Mục Danh sách Đánh số với Giá trị Tùy chỉnh

Sử dụng BulletFormat.setNumberedBulletStartWith để thiết lập số ban đầu hiển thị cho một đoạn có số.

  1. Tạo một Presentation và thêm một AutoShape vào một slide.
  2. Xóa đoạn mặc định khỏi khung văn bản của hình dạng.
  3. Tạo ba đoạn có số.
  4. Đặt BulletFormat.setNumberedBulletStartWith thành 2, 3 và 7 cho các đoạn tương ứng.
  5. Thêm các đoạn vào khung văn bản và lưu bản trình bày.

Ví dụ Python này gán số bắt đầu tùy chỉnh cho mỗi đoạn:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import BulletType, Paragraph, Presentation, SaveFormat, ShapeType

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 200, 200, 400, 200)
    text_frame = shape.getTextFrame()
    text_frame.getParagraphs().clear()
    first_paragraph = Paragraph()
    first_paragraph.setText("Start at 2")
    first_paragraph.getParagraphFormat().getBullet().setType(BulletType.Numbered)
    first_paragraph.getParagraphFormat().getBullet().setNumberedBulletStartWith(2)
    text_frame.getParagraphs().add(first_paragraph)
    second_paragraph = Paragraph()
    second_paragraph.setText("Start at 3")
    second_paragraph.getParagraphFormat().getBullet().setType(BulletType.Numbered)
    second_paragraph.getParagraphFormat().getBullet().setNumberedBulletStartWith(3)
    text_frame.getParagraphs().add(second_paragraph)
    third_paragraph = Paragraph()
    third_paragraph.setText("Start at 7")
    third_paragraph.getParagraphFormat().getBullet().setType(BulletType.Numbered)
    third_paragraph.getParagraphFormat().getBullet().setNumberedBulletStartWith(7)
    text_frame.getParagraphs().add(third_paragraph)
    presentation.save("custom_numbered_list.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

Kiểm soát Bố cục Đoạn và Thuộc tính Cuối Đoạn

Đặt Thụt lề Dòng Đầu

Sử dụng ParagraphFormat.setIndent để kiểm soát thụt lề dòng đầu của một đoạn. Phương thức này chỉ di chuyển dòng đầu so với lề trái của đoạn. Giá trị dương dịch dòng đầu sang phải, trong khi các dòng còn lại vẫn căn chỉnh với thân đoạn.

Sử dụng ParagraphFormat.setMarginLeft khi bạn cần di chuyển toàn bộ đoạn. Dùng ParagraphFormat.setIndent khi bạn chỉ muốn di chuyển dòng đầu.

Ví dụ dưới tạo một số đoạn và áp dụng các giá trị khác nhau của ParagraphFormat.setIndent để minh họa cách thụt lề dòng đầu ảnh hưởng đến bố cục đoạn.

  1. Tạo một thể hiện của lớp Presentation.
  2. Truy cập slide mục tiêu.
  3. Thêm một AutoShape hình chữ nhật vào slide.
  4. Truy cập TextFrame của hình dạng và xóa đoạn mặc định.
  5. Tạo một số đoạn và đặt các giá trị ParagraphFormat.setIndent khác nhau cho chúng.
  6. Thêm các đoạn vào khung văn bản.
  7. Lưu bản trình bày đã sửa đổi.

Đoạn mã này cho bạn thấy cách đặt thụt lề cho một đoạn:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import FillType, Paragraph, Presentation, SaveFormat, ShapeType, TextAutofitType
from java.awt import Color

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 50, 50, 420, 220)
    shape.getFillFormat().setFillType(FillType.NoFill)
    shape.getLineFormat().getFillFormat().setFillType(FillType.Solid)
    shape.getLineFormat().getFillFormat().getSolidFillColor().setColor(Color.GRAY)
    text_frame = shape.getTextFrame()
    text_frame.getTextFrameFormat().setAutofitType(TextAutofitType.Shape)
    text_frame.getParagraphs().clear()
    first_paragraph = Paragraph()
    first_paragraph.setText("No first-line indent. Wrapped lines start at the same position as the first line.")
    first_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    first_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    first_paragraph.getParagraphFormat().setMarginLeft(20.0)
    first_paragraph.getParagraphFormat().setIndent(0.0)
    second_paragraph = Paragraph()
    second_paragraph.setText("First-line indent of 20 points. The first line moves to the right, while wrapped lines remain aligned to the paragraph body.")
    second_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    second_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    second_paragraph.getParagraphFormat().setMarginLeft(20.0)
    second_paragraph.getParagraphFormat().setIndent(20.0)
    third_paragraph = Paragraph()
    third_paragraph.setText("First-line indent of 40 points. This paragraph shows a larger first-line offset to make the effect easier to see.")
    third_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    third_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    third_paragraph.getParagraphFormat().setMarginLeft(20.0)
    third_paragraph.getParagraphFormat().setIndent(40.0)
    text_frame.getParagraphs().add(first_paragraph)
    text_frame.getParagraphs().add(second_paragraph)
    text_frame.getParagraphs().add(third_paragraph)
    presentation.save("paragraph_indent.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

Kết quả:

Thụt lề dòng đầu của các đoạn

Đặt Thụt lề Treo

Thụt lề treo là bố cục đoạn mà trong đó dòng đầu bắt đầu ở bên trái của các dòng còn lại. Trong Aspose.Slides, bạn tạo hiệu ứng này bằng ParagraphFormat.setIndent. Cung cấp một giá trị âm để dịch dòng đầu sang trái so với thân đoạn.

Trong thực tế, ParagraphFormat.setMarginLeft xác định vị trí trái của thân đoạn, và ParagraphFormat.setIndent xác định vị trí của dòng đầu so với lề đó. Để tạo thụt lề treo, cung cấp một giá trị dương cho ParagraphFormat.setMarginLeft và một giá trị âm cho ParagraphFormat.setIndent.

Định dạng này hữu ích cho thư tịch, tài liệu tham khảo, mục từ điển và các đoạn khác nơi các dòng gập cần căn dưới thân đoạn thay vì dưới ký tự đầu tiên của dòng đầu.

  1. Tạo một thể hiện của lớp Presentation.
  2. Truy cập slide mục tiêu.
  3. Thêm một AutoShape hình chữ nhật vào slide.
  4. Truy cập TextFrame của hình dạng và xóa đoạn mặc định.
  5. Tạo các đoạn và cung cấp một giá trị dương cho ParagraphFormat.setMarginLeft cho mỗi đoạn.
  6. Cung cấp một giá trị âm cho ParagraphFormat.setIndent để tạo hiệu ứng thụt lề treo.
  7. Thêm các đoạn vào khung văn bản.
  8. Lưu bản trình bày đã sửa đổi.

Đoạn mã này cho bạn thấy cách đặt thụt lề treo cho một đoạn:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import FillType, Paragraph, Presentation, SaveFormat, ShapeType, TextAutofitType
from java.awt import Color

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 50, 50, 420, 220)
    shape.getFillFormat().setFillType(FillType.NoFill)
    shape.getLineFormat().getFillFormat().setFillType(FillType.Solid)
    shape.getLineFormat().getFillFormat().getSolidFillColor().setColor(Color.GRAY)
    text_frame = shape.getTextFrame()
    text_frame.getTextFrameFormat().setAutofitType(TextAutofitType.Shape)
    text_frame.getParagraphs().clear()
    first_paragraph = Paragraph()
    first_paragraph.setText("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.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    first_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    first_paragraph.getParagraphFormat().setMarginLeft(40.0)
    first_paragraph.getParagraphFormat().setIndent(-20.0)
    second_paragraph = Paragraph()
    second_paragraph.setText("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.getParagraphFormat().getDefaultPortionFormat().getFillFormat().setFillType(FillType.Solid)
    second_paragraph.getParagraphFormat().getDefaultPortionFormat().getFillFormat().getSolidFillColor().setColor(Color.BLACK)
    second_paragraph.getParagraphFormat().setMarginLeft(60.0)
    second_paragraph.getParagraphFormat().setIndent(-30.0)
    text_frame.getParagraphs().add(first_paragraph)
    text_frame.getParagraphs().add(second_paragraph)
    presentation.save("hanging_indent.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

Kết quả:

Thụt lề treo của các đoạn

Đặt Thuộc tính Đoạn Kết thúc

Paragraph.setEndParagraphPortionFormat kiểm soát định dạng của ký hiệu kết thúc đoạn. Ví dụ sau gán kích thước phông chữ và phông Latin cho ký hiệu kết thúc của đoạn thứ hai:

  1. Tải một Presentation và truy cập một slide.
  2. Thêm một AutoShape và xóa đoạn mặc định của nó.
  3. Tạo hai đoạn và thêm các phần văn bản vào chúng.
  4. Tạo một PortionFormat cho ký hiệu kết thúc của đoạn thứ hai.
  5. Đặt BasePortionFormat.setFontHeight và BasePortionFormat.setLatinFont.
  6. Gán định dạng bằng Paragraph.setEndParagraphPortionFormat và lưu bản trình bày.
import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import FontData, Paragraph, Portion, PortionFormat, Presentation, SaveFormat, ShapeType

presentation = Presentation("Test.pptx")
try:
    slide = presentation.getSlides().get_Item(0)
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 10, 10, 200, 250)
    text_frame = shape.getTextFrame()
    text_frame.getParagraphs().clear()
    first_paragraph = Paragraph()
    first_portion = Portion("Sample text")
    first_paragraph.getPortions().add(first_portion)
    second_paragraph = Paragraph()
    second_portion = Portion("Sample text 2")
    second_paragraph.getPortions().add(second_portion)
    end_paragraph_format = PortionFormat()
    end_paragraph_format.setFontHeight(48)
    latin_font = FontData("Times New Roman")
    end_paragraph_format.setLatinFont(latin_font)
    second_paragraph.setEndParagraphPortionFormat(end_paragraph_format)
    text_frame.getParagraphs().add(first_paragraph)
    text_frame.getParagraphs().add(second_paragraph)
    presentation.save("end_paragraph_format.pptx", SaveFormat.Pptx)
finally:
    presentation.dispose()

Đếm Số Dòng Được Render

Đối với các quy tắc đoạn ảnh hưởng tới việc cuộn tự động và dấu chấm câu ở cuối dòng, xem Control Line Breaking và Control Hanging Punctuation.

Sử dụng Paragraph.getLinesCount để đếm số dòng mà một đoạn chiếm sau khi bố cục văn bản, bao gồm cả cuộn tự động. Điều này hữu ích khi kiểm tra độ dài và bố cục văn bản trong các mẫu bản trình bày.

Một đoạn là một mục trong TextFrame.getParagraphs, và nó có thể chiếm nhiều dòng đã render. Một ngắt dòng rõ ràng bên trong đoạn buộc một dòng mới mà không tạo đoạn mới. Cuộn tự động tạo các dòng dựa trên chiều rộng khả dụng mà không chèn ngắt dòng rõ ràng vào văn bản. Do đó việc chỉ đếm các đoạn hoặc ký tự ngắt dòng không cho ra số dòng đã render.

Ví dụ sau tạo một hình dạng văn bản, đếm các dòng của nó, thu hẹp hình dạng, và sau đó thay thế văn bản bằng một chuỗi ngắn hơn. Cuộn được bật và tự động vừa kích thước được tắt để chiều rộng hình dạng kiểm soát việc cuộn mà không thu nhỏ tự động văn bản hoặc thay đổi kích thước hình dạng. Kích thước hình dạng tính bằng điểm. Cuối cùng, ví dụ thêm một đoạn nữa và cộng tổng số dòng trong khung văn bản.

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import NullableBool, Paragraph, Presentation, ShapeType, TextAutofitType

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)

    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 50, 50, 400, 200)
    text_frame = shape.getTextFrame()
    text_frame.getTextFrameFormat().setWrapText(NullableBool.True_)
    text_frame.getTextFrameFormat().setAutofitType(TextAutofitType.None_)

    paragraph = text_frame.getParagraphs().get_Item(0)
    paragraph.getParagraphFormat().getDefaultPortionFormat().setFontHeight(20)
    paragraph.setText("This text demonstrates how automatic wrapping changes the number of rendered lines.")
    print("Original width:", paragraph.getLinesCount())

    shape.setWidth(150)
    print("Narrower shape:", paragraph.getLinesCount())

    paragraph.setText("Short text.")
    print("Shorter text:", paragraph.getLinesCount())

    second_paragraph = Paragraph()
    second_paragraph.setText("Another paragraph.")
    second_paragraph.getParagraphFormat().getDefaultPortionFormat().setFontHeight(20)
    text_frame.getParagraphs().add(second_paragraph)

    total_line_count = 0
    for current_paragraph in text_frame.getParagraphs():
        total_line_count += current_paragraph.getLinesCount()
    print("Total lines in the text frame:", total_line_count)
finally:
    presentation.dispose()

Với văn bản và các kích thước này, thu hẹp hình dạng làm tăng số dòng, trong khi thay thế văn bản bằng chuỗi ngắn làm giảm số dòng. Các số đếm chính xác có thể khác nhau tùy vào sự sẵn có và thay thế phông chữ, kích thước phông, lề, thụt lề, cuộn và cài đặt tự động vừa. Sử dụng các phông và cài đặt bố cục dự kiến cho môi trường mục tiêu khi kiểm tra mẫu.

Số dòng một mình không quyết định liệu văn bản có tràn khỏi vùng chứa hay không. Chiều cao khả dụng, chiều cao dòng, khoảng cách đoạn và dòng, và hành vi tự động vừa cũng quan trọng; ngay cả một dòng duy nhất cũng có thể vượt quá chiều rộng khi tắt cuộn.

Nhập và Xuất Nội dung Đoạn

Nhập Văn bản HTML vào Đoạn

Sử dụng ParagraphCollection.addFromHtml để chuyển đổi markup HTML thành các đoạn và phần trong một khung văn bản.

  1. Tạo một thể hiện của lớp Presentation.
  2. Truy cập một slide và thêm một AutoShape.
  3. Truy cập TextFrame của hình dạng và xóa đoạn mặc định.
  4. Đọc tệp HTML nguồn.
  5. Đưa chuỗi HTML vào ParagraphCollection.addFromHtml.
  6. Lưu bản trình bày đã sửa đổi.

Ví dụ Python này nhập HTML vào một khung văn bản:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import FillType, Presentation, SaveFormat, ShapeType
from pathlib import Path

presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    shape_width = presentation.getSlideSize().getSize().getWidth() - 20
    shape_height = presentation.getSlideSize().getSize().getHeight() - 20
    shape = slide.getShapes().addAutoShape(ShapeType.Rectangle, 10, 10, shape_width, shape_height)
    shape.getFillFormat().setFillType(FillType.NoFill)
    shape.getTextFrame().getParagraphs().clear()
    try:
        html = Path("file.html").read_text(encoding="utf-8")
        shape.getTextFrame().getParagraphs().addFromHtml(html)
        presentation.save("html_text.pptx", SaveFormat.Pptx)
    except OSError as exception:
        print("The HTML file could not be read: " + str(exception))
finally:
    presentation.dispose()

Xuất Văn bản Đoạn ra HTML

Sử dụng ParagraphCollection.exportToHtml để xuất một phạm vi đoạn được chọn dưới dạng HTML.

  1. Tạo một thể hiện của lớp Presentation và tải bản trình bày mong muốn.
  2. Truy cập slide và tìm AutoShape chứa văn bản.
  3. Truy cập TextFrame của hình dạng.
  4. Gọi ParagraphCollection.exportToHtml với chỉ mục đoạn bắt đầu và số lượng đoạn cần xuất.
  5. Ghi chuỗi HTML trả về vào tệp.

Ví dụ Python này xuất toàn bộ các đoạn từ khung văn bản đầu tiên:

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import AutoShape, Presentation
from pathlib import Path

presentation = Presentation("ExportingHTMLText.pptx")
try:
    shape = presentation.getSlides().get_Item(0).getShapes().get_Item(0)
    if isinstance(shape, AutoShape):
        text_shape = shape
        text_frame = text_shape.getTextFrame()
        if text_frame is not None:
            paragraphs = text_frame.getParagraphs()
            html = paragraphs.exportToHtml(0, paragraphs.getCount(), None)
            try:
                Path("paragraphs.html").write_text(str(html), encoding="utf-8")
            except OSError as exception:
                print("The HTML file could not be written: " + str(exception))
        else:
            print("The first shape does not contain a text frame.")
    else:
        print("The first shape is not a text shape.")
finally:
    presentation.dispose()

Render Đoạn dưới Dạng Ảnh

Paragraph.getImage render một đoạn riêng lẻ trực tiếp và trả về một đối tượng ảnh. Lưu kết quả vào tệp hoặc luồng bằng phương thức save của nó. Bạn không cần render hình dạng chứa hoặc cắt ảnh bitmap thủ công.

Paragraph.getImage có thể trả về None nếu không tìm thấy đoạn trong bộ sưu tập cha, không có vùng render hợp lệ, hoặc không thể render. Kiểm tra kết quả trước khi lưu và giải phóng ảnh trả về sau khi sử dụng.

Render Đoạn ở Tỷ lệ Mặc định

Giả sử chúng ta có một tệp bản trình bày có tên sample.pptx với một slide, trong đó hình dạng đầu tiên là một ô văn bản chứa ba đoạn.

Ô văn bản với ba đoạn

Ví dụ sau render đoạn thứ hai trong một hình dạng văn bản thường tại tỷ lệ mặc định và lưu ảnh trả về dưới dạng PNG. Khối finally đảm bảo ảnh được giải phóng đúng cách.

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import AutoShape, ImageFormat, Presentation

presentation = Presentation("sample.pptx")
try:
    shape = presentation.getSlides().get_Item(0).getShapes().get_Item(0)
    if isinstance(shape, AutoShape):
        text_shape = shape
        text_frame = text_shape.getTextFrame()
        if text_frame is not None and text_frame.getParagraphs().getCount() > 1:
            paragraph = text_frame.getParagraphs().get_Item(1)
            paragraph_image = paragraph.getImage()
            if paragraph_image is not None:
                try:
                    paragraph_image.save("paragraph.png", ImageFormat.Png)
                finally:
                    paragraph_image.dispose()
            else:
                print("The paragraph could not be rendered.")
        else:
            print("The expected paragraph was not found.")
    else:
        print("The first shape is not a text shape.")
finally:
    presentation.dispose()

Kết quả:

Ảnh đoạn

Render Đoạn trong Ô Bảng với Tỷ lệ Phóng To

Sử dụng overload của Paragraph.getImage cho phép truyền các tham số scale_x và scale_y để đặt hệ số phóng to chiều ngang và chiều dọc. Ví dụ sau tạo một bảng, render đoạn trong ô đầu tiên với độ rộng và chiều cao gấp đôi mặc định, và lưu kết quả dưới dạng PNG.

import jpype
import asposeslides

if not jpype.isJVMStarted():
    jpype.startJVM()

from asposeslides.api import ImageFormat, Presentation

scale_x = 2.0
scale_y = 2.0
presentation = Presentation()
try:
    slide = presentation.getSlides().get_Item(0)
    table = slide.getShapes().addTable(50, 50, [300.0], [80.0])
    paragraph = table.get_Item(0, 0).getTextFrame().getParagraphs().get_Item(0)
    paragraph.setText("Text in a table cell")
    paragraph_image = paragraph.getImage(scale_x, scale_y)
    if paragraph_image is not None:
        try:
            paragraph_image.save("table_paragraph.png", ImageFormat.Png)
        finally:
            paragraph_image.dispose()
    else:
        print("The paragraph could not be rendered.")
finally:
    presentation.dispose()

Hệ số 1 giữ trục ở kích thước pixel mặc định. Ví dụ, 2 cho cả hai trục tạo ra một ảnh có chiều rộng và chiều cao gần gấp đôi kích thước mặc định, tương đương bốn lần số pixel. Các hệ số lớn hơn thường tạo ra văn bản sắc nét hơn cho việc phóng to hoặc xuất ra độ phân giải cao, nhưng cũng làm tăng bộ nhớ và kích thước tệp. Hệ số dưới 1 tạo ảnh nhỏ hơn với ít chi tiết hơn. Sử dụng các hệ số bằng nhau để giữ tỷ lệ khung hình của đoạn; các hệ số ngang và dọc khác nhau sẽ kéo dài đầu ra một cách độc lập.

Render toàn bộ hình dạng bằng Shape.getImage vẫn hữu ích khi đầu ra cần bao gồm nền, viền hoặc ngữ cảnh hình ảnh khác của hình dạng. Đối với ảnh chỉ chứa đoạn, hãy dùng Paragraph.getImage.

Câu hỏi thường gặp

Có thể tắt hoàn toàn việc cuộn dòng trong khung văn bản không?

Có. Đặt TextFrameFormat.setWrapText để tắt cuộn, vì vậy các dòng sẽ không ngắt ở cạnh khung văn bản.

Làm sao để lấy vị trí chính xác trên slide của một đoạn cụ thể?

Sử dụng Paragraph.getRect để lấy hình chữ nhật bao quanh đoạn. Portion.getRect cung cấp vị trí của một phần riêng lẻ.

Nơi nào điều chỉnh căn chỉnh đoạn (trái, phải, giữa hoặc canh đều)?

ParagraphFormat.setAlignment là cài đặt ở mức đoạn và áp dụng cho toàn bộ đoạn bất kể định dạng phần riêng lẻ.

Để căn chỉnh dọc các phần có kích thước phông chữ khác nhau trong mỗi dòng, xem Align Fonts Within a Line.

Có thể đặt ngôn ngữ kiểm tra chính tả cho một phần của đoạn không?

Có. Đặt BasePortionFormat.setLanguageId cho các phần riêng lẻ, vì vậy một đoạn có thể chứa văn bản bằng nhiều ngôn ngữ.