Python에서 PowerPoint 텍스트 단락 관리
개요
Aspose.Slides for Python via .NET는 텍스트를 텍스트 프레임, 단락 및 구간의 계층 구조로 나타냅니다:
- TextFrame은 도형 내의 텍스트 컨테이너를 나타내며 단락 컬렉션에 접근할 수 있게 합니다.
- Paragraph은 텍스트 프레임 내의 하나의 단락을 나타내며 구간 및 단락 수준 서식에 접근할 수 있게 합니다.
- Portion은 단락 내의 텍스트 실행을 나타냅니다. 각 구간은 자체 텍스트와 문자 수준 서식을 가질 수 있습니다.
따라서 단락은 여러 구간을 사용하여 서로 다른 글꼴, 색상, 크기 및 기타 서식이 적용된 텍스트를 포함할 수 있습니다.
단락 만들기 및 서식 지정
도형의 텍스트 프레임에서 단락을 만들고 구간을 사용하여 개별 텍스트 실행을 서식 지정합니다. 이 섹션에서는 각 단락에 여러 구간을 결합하고 색상, 글꼴 크기 및 스타일을 다르게 적용하는 방법을 보여줍니다.
여러 구간이 있는 단락 만들기
다음 Python 예제는 세 개의 단락을 만들고, 각 단락의 Paragraph.portions 컬렉션에 세 개의 텍스트 실행을 포함합니다. 기본 단락과 비어 있는 구간을 재사용한 후 나머지 단락과 구간을 추가합니다. 서식은 Portion.portion_format을 통해 적용됩니다. 각 단락의 첫 번째 구간은 빨간색, 굵게, 15pt이며, 두 번째는 파란색, 기울임, 18pt입니다. 세 번째 구간은 기본 서식을 유지합니다:
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%이고 단락 들여쓰기가 25pt인 검은색 글머리표를 사용합니다:
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 20pt와 ParagraphFormat.indent 값을 각각 0, 20, 40pt로 지정합니다. 첫 줄은 점차 큰 오프셋에서 시작하고, 줄 바꿈된 줄은 동일한 왼쪽 여백을 유지합니다:
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과 60pt로, ParagraphFormat.indent 값을 각각 -20과 -30pt로 지정합니다. 각 단락에서는 첫 줄이 줄 바꿈된 줄보다 왼쪽에 시작되며, 두 번째 단락은 더 깊은 행걸이 들여쓰기를 가집니다:
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를 48pt, 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에 전달합니다. 텍스트 프레임의 기본 단락을 지워 가져온 내용만 포함하도록 합니다. 사각형 도형은 슬라이드 각 면에 10pt 여백을 남깁니다:
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을 설정하여 서식 상속을 어느 정도까지 따를지 제어합니다.
샘플 프레젠테이션(the sample presentation)을 다운로드하고 애플리케이션 작업 디렉터리에 배치합니다. 첫 슬라이드에는 텍스트 “Inherited text; explicit red 18pt"가 포함된 하나의 텍스트 도형이 있습니다. 입력은 의도적으로 여러 서식 레벨을 사용합니다:
- 프레젠테이션 기본 텍스트 스타일은 Calibri 28pt를 제공합니다.
- 텍스트 프레임의 1단계 텍스트 스타일은 파란색 텍스트와 기울임꼴을 제공합니다.
- 단락은 명시적으로 굵은 텍스트를 설정합니다.
- 두 번째 구간 “explicit red 18pt"는 빨간색 텍스트와 18pt 크기를 명시적으로 설정합니다.
다음 완전한 예제는 동일한 단락을 세 번 내보냅니다. 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가 사용 가능하면 28pt, 파란색, 굵게, 기울임꼴 |
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이 사용되는 위치에 따라 달라집니다.
HTML 클립보드 조각 생성
ParagraphCollection.export_to_html은 HTML 문자열을 반환합니다. TextToHtmlConversionOptions.add_clipboard_fragment_header를 False로 설정하면 일반 HTML을, True로 설정하면 Windows 클립보드 헤더가 포함된 HTML 조각을 반환합니다. 헤더는 주변 HTML(StartHTML 및 EndHTML)과 붙여넣을 조각(StartFragment 및 EndFragment)의 UTF‑8 바이트 오프셋을 제공합니다.
이 예제는 두 개의 서식 지정된 단락을 일반 HTML(html)과 클립보드 조각(clipboard_html)으로 내보냅니다. 조각을 시스템 클립보드에 쓰는 작업은 별도의 애플리케이션 단계입니다. 클립보드 API가 원시 바이트를 기대한다면, BOM 없이 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)
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를 사용하십시오.
FAQ
텍스트 프레임 내부에서 줄 바꿈을 완전히 비활성화할 수 있나요?
예. TextFrameFormat.wrap_text을 설정하면 텍스트 프레임 가장자리에 줄이 끊기지 않도록 줄 바꿈을 비활성화합니다.
특정 단락의 슬라이드 내 정확한 경계 사각형을 가져오려면 어떻게 해야 하나요?
Paragraph.get_rect을 사용하면 단락의 경계 사각형을 가져올 수 있습니다. Portion.get_rect은 개별 구간의 경계를 제공합니다.
단락 정렬(왼쪽, 오른쪽, 가운데, 양쪽 맞춤)은 어디서 제어하나요?
ParagraphFormat.alignment은 단락 수준 설정이며, 개별 구간 서식과 무관하게 전체 단락에 적용됩니다.
각 라인에서 서로 다른 글꼴 크기의 구간을 수직 정렬하려면 Align Fonts Within a Line를 참조하십시오.
단락의 일부에 교정 언어를 설정할 수 있나요?
예. PortionFormat.language_id을 개별 구간에 설정하면 하나의 단락에 여러 언어의 텍스트를 포함시킬 수 있습니다.