Search code examples
pythonpython-3.xdocxpython-docx

Python changing color and style of the hyperlink in docx


I add a add_hyperlink function in my code and I can add hyperlinks in to my document with this function but when I want to change their color, I can't do that. Here is the function:

    def add_hyperlink(paragraph, url, text):
        part = paragraph.part
        r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
        hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
        hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )
        new_run = docx.oxml.shared.OxmlElement('w:r')
        rPr = docx.oxml.shared.OxmlElement('w:rPr')
        new_run.append(rPr)
        new_run.text = text
        hyperlink.append(new_run)
        paragraph._p.append(hyperlink)
        return hyperlink

I tried to change it with using

hyperl = add_hyperlink(paragraph, 'https://stackoverflow.com', 'stackoverflow')
hyperl.font.color.rgb = RGBColor(0x99, 0x99, 0x99)

But it didn't work. I'm trying to do this for days. Is it possible to change the color or the style of the hyperlink from code?


Solution

  • I solved the problem. I added these lines top of the return hyperlink line in the function

    r = paragraph.add_run()
    r._r.append (hyperlink)
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK