Python-pptx - Text parameters (font, size, position) on Autoshape

假如想象 提交于 2019-12-10 21:54:16

问题


How can I set font, size of text for the shape ?

One Object instead two seperate ones (shape and Text, how use run for the shape)

Just do not get how to set the parameters on Textframe instance of the Autoshape-object.

from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.enum.dml import MSO_THEME_COLOR
from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE
from pptx.util import Inches, Pt

prs = Presentation('Input.pptx')
slide_layout = prs.slide_layouts[2]
slide = prs.slides.add_slide(slide_layout)
shape = slide.shapes
#Title
shape.title.text = "Title of the slide"
# Shape position
left = Inches(0.5)
top = Inches(1.5)
width = Inches(2.0)
height = Inches(0.2)

box = shape.add_shape(MSO_SHAPE.RECTANGLE, left, top, width, height)
#Fill
fill = box.fill
line = box.line
fill.solid()
fill.fore_color.theme_color = MSO_THEME_COLOR.ACCENT_2
line.color.theme_color = MSO_THEME_COLOR.ACCENT_2
# How can I set font, size of text for the shape ?
# One Object for instead two seperate ones
#box_text.font.bold = True

# Text position
t_left = Inches(0.5)
t_top = Inches(1.4)
t_width = Inches(2.0)
t_height = Inches(0.4)
#Text
txBox = slide.shapes.add_textbox(t_left, t_top, t_width,t_height)
tf = txBox.text_frame.paragraphs[0]
tf.vertical_anchor = MSO_ANCHOR.TOP
tf.word_wrap = False
tf.margin_top = 0
tf.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT
run = tf.add_run()
run.text = "Text on the Shape"
font = run.font
font.name = 'Calibri'
font.size = Pt(18)
font.bold = True
font.italic = None  # cause value to be inherited from theme
font.color.theme_color = MSO_THEME_COLOR.ACCENT_5
prs.save('Out.pptx')

回答1:


If you want non-default character formatting (font) in a shape, you need to operate at the Run level; that's where the character formatting lives and is pretty much the entire reason for having runs instead of just paragraphs.

So a simple example:

from pptx.util import Pt

shape = shapes.add_shape(MSO_SHAPE.RECTANGLE, left, top, width, height)
text_frame = shape.text_frame
text_frame.clear()  # not necessary for newly-created shape

p = text_frame.paragraphs[0]
run = p.add_run()
run.text = 'Spam, eggs, and spam'

font = run.font
font.name = 'Calibri'
font.size = Pt(18)
font.bold = True

By adding more runs to the paragraph, you can have, for example, bold words inside a sentence of normally formatted words, etc.

More details at and around: http://python-pptx.readthedocs.io/en/latest/user/text.html#applying-character-formatting



来源:https://stackoverflow.com/questions/45633385/python-pptx-text-parameters-font-size-position-on-autoshape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!