如何使用pythondocx在msword中添加页面间链接?

2024-05-15 23:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个文件,其中包含前4页的文本数据和第5页以后的所有图像。在

有一个以页码为列的表格。我想添加到该列中的每个页码的链接,通过单击该链接可以获得该页码引用的图像页面。在

我使用python docx创建这个文档。在

在google上遇到麻烦时,我得到了一个使用pythondocx创建超链接的解决方案。单击带有超链接的文本将带我到它引用的url。在

超链接的代码如下:

import docx
from docx.enum.dml import MSO_THEME_COLOR_INDEX

def add_hyperlink(paragraph, text, url):
    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)

    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )

    # Create a w:r element and a new w:rPr element
    new_run = docx.oxml.shared.OxmlElement('w:r')
    rPr = docx.oxml.shared.OxmlElement('w:rPr')

    # Join all the xml elements together add add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)

    # Create a new Run object and add the hyperlink into it
    r = paragraph.add_run ()
    r._r.append (hyperlink)

    # A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
    # Delete this if using a template that has the hyperlink style in it
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True

    return hyperlink


document = docx.Document()
p = document.add_paragraph('A plain paragraph having some ')
add_hyperlink(p, 'Link to Google', "http://google.com")
document.save('demo_hyperlink.docx')

我希望链接指向内部文档页面。在


Tags: andthetoruntextaddidnew