Coverage for src/botadi/mokadi/pptx_helper.py: 93%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

29 statements  

1""" 

2@file 

3@brief Helpers on Powerpoint presentation. 

4It relies on module `python-pptx <https://python-pptx.readthedocs.io/en/latest/>`_. 

5""" 

6 

7 

8def pptx_enumerate_text(ptx): 

9 """ 

10 Enumerates all text content in a presentation. 

11 

12 @param ptx presentation 

13 @return enumerate (slide, shape, zone, text) 

14 """ 

15 for islide, slide in enumerate(ptx.slides): 

16 for ishape, shape in enumerate(slide.shapes): 

17 if not shape.has_text_frame: 

18 continue 

19 text_frame = shape.text_frame 

20 for ip, p in enumerate(text_frame.paragraphs): 

21 if p.text: 

22 yield (islide, ishape, ip, p.text) 

23 

24 

25def pptx_apply_transform(ptx, replace_func): 

26 """ 

27 Applies the same transformation on all text zone. 

28 

29 @param ptx presentation 

30 @param replace_func function ``f(islide, ishape, ip, text) --> text 

31 @return presentation 

32 

33 @warning Updated text does not retain style (bug). 

34 """ 

35 from pptx.util import Pt 

36 from pptx.dml.color import RGBColor 

37 

38 for islide, slide in enumerate(ptx.slides): 

39 for ishape, shape in enumerate(slide.shapes): 

40 if not shape.has_text_frame: 

41 continue 

42 text_frame = shape.text_frame 

43 for ip, p in enumerate(text_frame.paragraphs): 

44 if p.text: 

45 new_text = replace_func(islide, ishape, ip, p.text) 

46 if new_text != p.text: 

47 font = p.font 

48 p.text = "" # new_text 

49 run = p.add_run() 

50 run.text = new_text 

51 run.font.name = font.name 

52 run.font.size = Pt(25) # font.size 

53 #run.font.color.rgb = font.color.rgb 

54 run.font.color.rgb = RGBColor(0xFF, 0x7F, 0x50) 

55 return ptx