How to add a link to a substring in python pptx?

46 Views Asked by At

I need to add some text with a link in a pptx slide. I need that only link points to a hyperlink. I tried to separate the text and created 2 paragraphs, 1 without a link and 1 with a link, but then I am having 2 pieces of text in different rows and I cannot merge them afterwards.
How can I set a link only on one word in python pptx?
Here is my code:

r1 = text_frame.paragraphs[0].add_run()
r1.text = 'some text with a '

r2 = text_frame.add_paragraph().add_run()
r2.text='link'
r2.hyperlink.address = 'google.com'
2

There are 2 best solutions below

0
Ani On

I used this answer: https://stackoverflow.com/a/56226142/13010940 and I changed the script like this:

r1 = text_frame.paragraphs[0].add_run()
r1.text = 'some text with a '

r2 = text_frame.paragraphs[0].add_run()
r2.text='link'
r2.hyperlink.address = 'google.com'

I found out that it is possible to add multiple runs in a single paragraph.

0
Hien Hoang On

Just need to modify the script a bit and it should do the work, I add underline and change it color to easily see the link. Below I run the full script to test it, change it to suite your need:

from pptx import Presentation
from pptx.util import Pt
from pptx.dml.color import RGBColor

# Create a presentation object
prs = Presentation()

# Add a slide
slide = prs.slides.add_slide(prs.slide_layouts[5])  # Using a blank slide layout

# Add a text frame
txBox = slide.shapes.add_textbox(left=Pt(100), top=Pt(100), width=Pt(500), height=Pt(50))
text_frame = txBox.text_frame

# Add a paragraph and runs
p = text_frame.paragraphs[0]
run1 = p.add_run()
run1.text = "some text with a "

run2 = p.add_run()
run2.text = "link"
run2.hyperlink.address = 'https://google.com'
run2.font.underline = True
run2.font.color.rgb = RGBColor(0, 0, 255)

# Continue the sentence
run3 = p.add_run()
run3.text = " in the sentence."

# Save the presentation
prs.save('example.pptx')

print("Presentation created successfully!")

The result: enter image description here