python-pptx How to set page top margin to 0

877 views Asked by At

I need to place text at the very top of the PPTX page.
There is always a 3/8 top margin. The code below sets fields to zero but the text start 3/8 inches from the top.

Library: python-pptx 0.6.18

ppt = Presentation()

ppt.slide_width = Inches(8.5)

ppt.slide_height = Inches(11)

left = top = Inches(0.0)

width = height = Inches(3.0)

txBox = slide.shapes.add_textbox(left, top, width, height)   

//# creating textFrames 
//# https://python-pptx.readthedocs.io/en/latest/user/text.html

tf = txBox.text_frame 

tf.word_wrap = False

tf.margin_top = Inches(0.0)     

tf.margin_bottom = Inches(0.0)

tf.margin_left = Inches(0.0)

tf.margin_right = Inches(0.0)   
                                
tf.vertical_anchor = MSO_ANCHOR.TOP                                        

p = tf.add_paragraph()  
p.alignment = PP_ALIGN.LEFT

Thx for help.

1

There are 1 answers

0
Justin Battaglia On

I have tried to set the margin to 0 doing this:

txBox.text_frame.margin_top = pptx.util.Inches(0)
txBox.text_frame.margin_bottom = pptx.util.Inches(0)

But it doesn't seem to change anything, there is still some margin on top and bottom. You can instead change the top value to a negative to put text at the very top of the page:

ppt = Presentation()

ppt.slide_width = Inches(8.5)

ppt.slide_height = Inches(11)

left = Inches(0.0)
top = Inches(-0.375)

width = height = Inches(3.0)

txBox = slide.shapes.add_textbox(left, top, width, height)  

This will force the top (y value) of the box to be moved higher than just 0 can do.