2017-08-11 322 views
0

如何設置字體,形狀文本的大小?

一個對象,而不是兩個單獨的人(形狀和文字,如何爲形狀使用運行)Python-pptx - Autoshape上的文本參數(字體,大小,位置)

只是不明白如何設置自選圖形對象的Textframe實例參數。

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') 
+0

https://stackoverflow.com/questions/45600820/how-do-you-set-the-font-size-of-a-chart-title-with-python-pptx這個問題似乎相關 –

回答

2

如果您想要在圖形中使用非默認字符格式(字體),您需要在運行級別進行操作;這就是字符格式化的地方,幾乎是運行而不是段落的全部原因。

所以一個簡單的例子:

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 

通過增加更多的運行段落,你可以有,例如,常格式化的話一句,等

更多細節在裏面大膽的話和周圍:http://python-pptx.readthedocs.io/en/latest/user/text.html#applying-character-formatting