Description
Hello! 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.