如何使用python-docx在MS Word中添加页面间链接? [英] How to add inter-page links in MS word using python-docx?

查看:843
本文介绍了如何使用python-docx在MS Word中添加页面间链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个文件,其中包含第1页第4页上的文本数据以及第5页以上的所有图像.

I am creating a file which contain text data on 1st 4 pages and all images from page 5 onwards.

有一个表,其中页码为列.我想通过单击该页面编号所引用的图像页面来为该列中的每个页面编号添加链接.

There is a table having page numbers as column. I want to add link to each of the page number in that column by clicking on which it should take me the the image page referenced by that page number.

我正在使用python-docx创建此文档.

I am creating this document using python-docx.

在google上绊脚石时,我得到了使用python-docx创建超链接的解决方案.单击带有超链接的文本会将我带到它所引用的URL.

While stumbling on google I got a solution for creating hyperlink using python-docx. Clicking on the text with hyperlink takes me to url referenced by it.

超链接的代码如下:

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')

我希望该链接指向内部文档页面.

I want that link to point to an inside document page.

推荐答案

我有完全相同的问题:

我从这里得到了答案您可以在此处

you can find an example of implementation here hyperlink to bookmark

享受 T

这篇关于如何使用python-docx在MS Word中添加页面间链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆