Hyperlinks
See original GitHub issueHello! I would like to know if it is possible to add an hyperlink to an existing portion of text. I have read the helper functions provided in past issues, but I did not find something helpful for me.
That’s the question: I have some text, for example, My name is Roberto and I am a lawyer (doc. 1) I would like to add an hyperlink to the string “doc. 1” (in the same way i may set an hyperlink in a word processor, just underlining text).
I have read the docs and it seems that hyperlink may be managed at Runs level. The problem is that i have not understood if I can set a Run inside an existing paragraph (without adding a new one).
# coding=utf-8
import docx
import hyperlink
import helpers
doc = docx.Document('atto.docx')
paragraphs = doc.paragraphs
txt = 'doc. 1'
for p in paragraphs:
runs = p.runs
for run in runs:
print run.text
if txt in run.text:
hyperlink.add(p, run, 'https://github.com')
run.font.color.rgb = docx.shared.RGBColor(0, 0, 255)
doc.save('new-atto.docx')
I tried this code (using the hyperlink function created by someone here, which adds the link to an existing run) but it does not work very well. I tried to set in the word processor “doc. 1” in bold (in order to assume that “doc.1” will be considered as a distinct run) but the implementation is quite buggy.
Could you please give me some advice ? (I am a lawyer and still inexperienced as developer 😃 )
@EDIT: if i change some styling in the string “doc. 1” in the original document, the above-mentioned will become a separate Run and the above code may work.
Issue Analytics
- State:
- Created 5 years ago
- Comments:7 (1 by maintainers)

Top Related StackOverflow Question
Here’s some code I threw together which will find some pattern in a run and replace it with a new run with the pattern text and then add the hyperlink to it. As far as I know there’s no way through the docx api to add a run after or before a given run, but through this post by @scanny I found the solution through lxml.etree._Element.
By the way, in the future I think the recommended forum for help is Stack Overflow using the “python-docx” tag.
Edit: There’s some goofiness with some periods being in different runs, so you might have to play with the pattern and how you edit the original text of the run. Sorry this isn’t more comprehensive, something I just threw together quickly. If you need more help I’d recommend making a stack overflow post and posting a link to it here.
@brasky The add_hyperlink_into_run function was extremely helpful to me for another use case. Thanks very much!