当前位置:  首页>> 技术小册>> Python与办公-玩转PPT

设置文本框的样式主要是控制框内文本的位置以及让太长的文本自动换行。

我们先来看一下调整文本位置的操作,主要是文本的偏移距离和垂直方向的对齐。看一下代码演示:

  1. from pptx import Presentation
  2. from pptx.enum.text import MSO_VERTICAL_ANCHOR
  3. from pptx.util import Pt
  4. ppt = Presentation()
  5. slide = ppt.slides.add_slide(ppt.slide_layouts[0])
  6. shape = slide.shapes[0]
  7. text_frame = shape.text_frame
  8. text_frame.text = "Of fice遇上了Python"
  9. # 文本位置偏移
  10. text_frame.margin_left = 0
  11. # text_frame.margin_top = Pt(50)
  12. # text_frame.margin_bottom = Pt(50)
  13. # text_frame.margin_right = Pt(50)
  14. # 垂直对齐方式
  15. text_frame.vertical_anchor = MSO_VERTICAL_ANCHOR.TOP # 居上对齐
  16. # text_frame.vertical_anchor = MSO_VERTICAL_ANCHOR.MIDDLE # 居中对齐
  17. # text_frame.vertical_anchor = MSO_VERTICAL_ANCHOR.BOTTOM # 居下对齐
  18. ppt.save("./ppt_ files/test.pptx")

文本的偏移距离是指文本距离文本框边缘的长度,TextFrame对象的margin_top、margin_bottom、margin_left、margin_right四个属性分别控制文本的上、下、左、右四个方向上与文本框边缘的距离。但是要注意的是,相反方向的偏移量会相互抵消,比如说把margin_top和margin_bottom的值都设置为50磅,则相当于上下方向没有任何移动;把margin_top设置为100磅,margin_bottom设置为60磅,结果就是文本向下移动了40磅。

文本的垂直方向的样式只有三种,那就是上对齐、中对齐和下对齐,这三个值都定义在MSO_VERTICAL_ANCHOR这个枚举类里,把它们赋值给TextFrame对象的vertical_anchor属性即可。需要注意的是,如果设置了垂直对齐,则margin_top和margin_bottom属性带来的垂直方向的偏移效果就会失效,即vertical_anchor属性的优先级高于margin_top和margin_bottom。

我们在新建一个文本框的时候会指定文本框的宽度,如果填充的文本长度超过了文本框的宽度,我们可以使用“\n”,即换行符让文本以多行显示,但这似乎比较麻烦。其实我们只要把TextFrame对象的word_wrap属性的值改为True,文本就会根据文本框的宽度自动换行了,代码如下:

  1. from pptx import Presentation
  2. from pptx.util import Cm
  3. ppt = Presentation()
  4. slide = ppt.slides.add_slide(ppt.slide_layouts[0])
  5. text_box = slide.shapes.add_textbox(Cm(3),Cm(5),Cm(10),Cm(5))
  6. text_frame = text_box.text_frame
  7. text_frame.text = "Of fice遇上了Python,从此它们就幸福地在一起了。" * 10
  8. # 文本自动换行
  9. text_frame.word_wrap = True
  10. ppt.save("./ppt_ files/test.pptx")