scanny / python-pptx

Create Open XML PowerPoint documents in Python
MIT License
2.4k stars 519 forks source link

Soft-carriage returns not working? #921

Closed FloGua closed 11 months ago

FloGua commented 11 months ago

I'm on Python 3.8.16 and python-pptx 0.6.22

I'm creating slides from an Excel table. I'm writing a paragraph in a text box placeholder. I want soft returns between three specific lines, but it gets converted to unicode.

This is one of the ways I tried to get it to work:

    # Text box to the right
    experiment_description = slide.placeholders[20].text_frame

    # Add the experiment details
    p = experiment_description.add_paragraph()
    # [...] first paragraph

    # Add experiment hypothesis
    p = experiment_description.add_paragraph()
    run = p.add_run()
    run.text = "Experiment hypothesis"
    run.font.bold = True

    p = experiment_description.add_paragraph()
    p.add_run().text = row['hypothesisIf']
    p.add_run().text = "\v" + row['hypothesisThen']
    p.add_run().text = "\v" + row['hypothesisBecause']

\n works fine, but I would like to have no space. I also tried to combine the data into one f"" string, but again \v gets converted.

It seems like there were previously issues solved as per https://pypi.org/project/python-pptx/#section-5 - any idea on what could I be doing wrong here?

scanny commented 11 months ago

Hmm, interesting. So the "\v" -> <a:br> behavior appears to be limited to paragraph text. This actually makes sense because you can't have a break in the middle of a run, only between runs. So a couple approaches I can think of:

p = experiment_description.add_paragraph(
    f"{row['hypothesisIf'}\v{row['hypothesisThen']}\v{row['hypothesisBecause']}"
)

OR

p = experiment_description.add_paragraph()
p.add_run().text = row['hypothesisIf']
p.add_line_break()
p.add_run().text = row['hypothesisThen']
p.add_line_break()
p.add_run().text = row['hypothesisBecause']

The latter approach is more verbose but has the advantage that you can set character formatting on each run individually.