Center-align text with Python-pptx

拈花ヽ惹草 提交于 2019-12-10 10:12:12

问题


Question in short: Is it possible to align text to the center in Python-pptx?

Since I'm using Python-pptx, I have been able to automate quite a lot of things and I really enjoy using it! However, I've run into a problem. I'm trying to center my text horizontally on a slide. If you don't understand me:

My text is now aligned to the left, similar to the text in the first two paragraphs. However, I'd like them to be aligned to the center, like those last two paragraphs. This is a snippet of my code:

left = Cm(3)
top = Cm(2.5)
width = Cm(15)
height = Cm(1)
txBox = slide.shapes.add_textbox(left, top, width, height)
tf = txBox.text_frame
p = tf.add_paragraph()
run = p.add_run()
run.text = "Just an example"
font = run.font
font.size = Pt(30)

I looked in the documentation, but couldn't find anything useful. I read something about "MSO_VERTICAL_ANCHOR" and "PP_PARAGRAPH_ALIGNMENT", but I just can't get it working.

Thank you in advance!


回答1:


from pptx.enum.text import PP_ALIGN

shape.paragraphs[0].alignment = PP_ALIGN.CENTER

This is taken directly from the Python pptx Docs. Does this not work for you? You said in your question that you've heard of PP_PARAGRAPH_ALIGNMENT but can't get it working. What problems are arising?

You can view more information regarding Python pptx alignment here.

Scanny, who commented below me added a wonderful point that will solve your problem:

Paragraph alignment (also known as justification) is a property of a paragraph and must be applied individually to each paragraph. In the code you included in your question, if you add a line p.alignment = PP_ALIGN.CENTER you should get what you're after.



来源:https://stackoverflow.com/questions/38935137/center-align-text-with-python-pptx

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