Adding a link to a bookmark in MS Word using pytho

2020-05-03 01:25发布

问题:

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?

回答1:

Never mind. 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