How can I change the character spacing in pptx-python?

643 Views Asked by At

What I try to do is change the spacing for each run in the function:

def add_direction_arrows(self):
    global junc_file, junc_file_name
    match_colors_to_type = {"White": RGBColor(255, 255, 255), "Yellow": RGBColor(238, 233, 23)}
    arrows_placeholders = {"NORTH_ARROWS": self.NO.LAN.Organize_arrows_order(),
                           "SOUTH_ARROWS": self.SO.LAN.Organize_arrows_order(),
                           "EAST_ARROWS": self.EA.LAN.Organize_arrows_order(),
                           "WEST_ARROWS": self.WE.LAN.Organize_arrows_order()}
    for slide in junc_file.slides:
        for shape in slide.shapes:
            if shape.name in arrows_placeholders.keys():
                text_frame = shape.text_frame
                text_frame.clear()
                arrows_list = arrows_placeholders[shape.name]
                for arrow in arrows_list:
                    text_frame = shape.text_frame
                    p = text_frame.paragraphs[0]
                    run = p.add_run()
                    run.text = arrow[0] * arrow[1]
                    font = run.font
                    font.bold = False
                  ➜ font.spacing = -10
                    font.size = Pt(49.9)
                    font.color.rgb = match_colors_to_type[arrow[2]]
    junc_file.save(junc_file_name)

I'm not sure if the python-pptx library includes this option, but if it doesn't, what other options do I have? is it possible to add it myself? maybe a way to manually 'press a button' in powerpoint? thanks!

2

There are 2 best solutions below

5
matthias On BEST ANSWER

According to the docs python-pptx does not support spacing.

You could take a deep dive into how the library is working internally, and probably add support yourself, but I doubt this is really an option for you.

You can of course edit the powerpoint files by hand later to change this (or even using VBA).

0
Svaeng On

Seems like there is no support for such. As a workaround, I used the following snippet to achieve the same in shape.table context. Maybe you can look into if it behaves the same for text runs by replacing the first two lines to get the text frame txBody.

def _set_char_spacing(cell):
    tc = cell._tc
    txBody = tc.get_or_add_txBody()
    if not len(txBody.p_lst) > 0:
      return cell

    p = txBody.p_lst[0] # NOTE: Using index 0 just for demo purposes
    r = p.r_lst[0] # NOTE: Using index 0 just for demo purposes
    if not r.rPr:
      rPr = r._add_rPr()

    spacing = Emu(40)
    rPr.attrib['spc'] = str(spacing)
    return cell

As a disclaimer, p_lst and r_lst are lists that would require iterating.