GeoffH
GeoffH

Reputation: 21

Adding a link to a bookmark in MS Word using python docx library

I've used the code from an earlier question to create a hyperlink: Adding an hyperlink in MSWord by using python-docx

I now want to create a link to a bookmark within the document, rather than an external hyperlink, but can't work out how to do it. Any ideas?

Upvotes: 0

Views: 3874

Answers (1)

GeoffH
GeoffH

Reputation: 21

Found a way, thanks to neilbilly at github: feature: Paragraph.add_hyperlink() #74

def add_link(paragraph, link_to, text):
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('w:anchor'), link_to, )
    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)
    r = paragraph.add_run ()
    r._r.append (hyperlink)
    r.font.name = "Calibri"
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True

Upvotes: 2

Related Questions