简体   繁体   中英

How do I add superscript/subscript text to Powerpoint using Python PPTX?

I would like to add superscript and subscript text to powerpoint slides using python pptx. When I try to change the superscript/subscript attributes no visual change occurs to the text on powerpoint. I have tried the following:

#Import modules
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.util import Cm


#Open powerpoint file
prs = Presentation('filename.pptx')

#Add slide
slidelayout = prs.slide_layouts[0]
slide = prs.slides.add_slide(slidelayout)
shapes = slide.shapes

#Add a shape
shape = shapes.add_shape(MSO_SHAPE.ROUNDED_RECTANGLE, Cm(10), Cm(10), Cm(10), Cm(10))

#Add text
text_frame = shape.text_frame
paragraph = text_frame.add_paragraph()
run = paragraph.add_run()
run.text = 'this text should be superscript'
font = run.font
font.superscript = True
font.subscript = False

#Save the powerpoint file
prs.save('filename2.pptx')

This might help you:

# Following functions are workarounds for python-pptx not having these functions for the font object
def set_subscript(font):
    font._element.set('baseline', '-25000')

def set_superscript(font):
    font._element.set('baseline', '30000')

def set_strikethrough(font):
    font._element.set('strike','sngStrike')

I have been able to copy in a superscript or shapes in text format from superscript generators like https://lingojam.com/TinyTextGenerator and then copy that into my string. I have used this in column names for tables. It shows up as a superscript in the code string when renaming the columns and also when output onto the powerpoint slide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM