Search code examples
pythonms-worddocxpython-docx

Python how to replace a word with a hyperlink in MS Word using docx?


I want to replace a word in my paragraph with a hyperlink. I saw functions that can create a new word with hyperlink but that's not what I want. For example I want to do something like this:

mydoc = docx.Document()
text = "a stackoverflow question"
parag = mydoc.add_paragraph(text)
parag.add_hyperlink(the word that will be changed to the hyperlink (in that case
                    that can be "stackoverflow"), link('https://stackoverflow.com'))

With this add_hyperlink function, the stackoverflow word must be a hyperlink. Is there any way to do this?


Solution

  • Build up the paragraph run by run, something like:

    document = docx.Document()
    paragraph = mydoc.add_paragraph()
    paragraph.add_run("a ")
    paragraph.add_hyperlink("stackoverflow", link('https://stackoverflow.com'))
    paragraph.add_run("question")
    

    A hyperlink must appear as its own run, so you need a separate run before and after if you want to put it in the middle of a sentence.