2

I would like to automate adding a highlight to a run of text (really a background colour) using python-pptx.

I've done a lot of work with python-pptx and have done a tiny amount of fiddling with _element in the past.

Could someone post a quick sample of highlighting a run of text using python-pptx? That I can work up into something fitting my need. (I don't care what the colour of the highlight is;I think there's some kind of enumeration of valid colours for this.)

Thanks!

Martin Packer
  • 648
  • 4
  • 12

1 Answers1

4

So, with a little reading of the code and guesswork I've got a complete working example:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pptx import Presentation, slide
from pptx.oxml.xmlchemy import OxmlElement
import xml.etree


prs = Presentation()

title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide( title_slide_layout )
title = slide.shapes.title
title.text = 'Presentation with Internal Hyperlinks'
tf = title.text_frame
p=tf.paragraphs[0]
run = p.add_run()
run.text="Hello"
rPr = run._r.get_or_add_rPr()

hl = OxmlElement("a:highlight")

srgbClr = OxmlElement("a:srgbClr")

setattr(srgbClr,'val','FFFF00')
hl.append(srgbClr)

rPr.append(hl)

prs.save( 'test.pptx' )

I can now package this up as a function which fiddles with a run - and add it to my main code.

Martin Packer
  • 648
  • 4
  • 12
  • 1
    one thing I noticed is that the line rPr = run._r.get_or_add_rPr() and everything afterward need to go exactly after run.text="Hello" . I was trying to set the font size first but then this code will not work – Atanas Atanasov Dec 15 '22 at 12:23
  • When using the rPr part of the code it works for LibreOffice and Google Slides, but the highlighting doesn't show in Powerpoint. – herman Aug 14 '23 at 08:09