【发布时间】:2020-01-17 19:17:37
【问题描述】:
我正在创建一个文件,其中包含第 4 页上的文本数据以及第 5 页以后的所有图像。
有一个以页码为列的表格。我想添加指向该列中每个页码的链接,方法是单击它应该将我带到该页码引用的图像页面。
我正在使用 python-docx 创建这个文档。
虽然在谷歌上磕磕绊绊,但我得到了一个使用 python-docx 创建超链接的解决方案。单击带有超链接的文本会将我带到它引用的 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')
我希望该链接指向内部文档页面。
【问题讨论】:
-
研究Word概念
Bookmark。书签是 Word“定位”链接的方式。那么你有两个选择:REF字段或Hyperlink字段。第一个是 Word 在创建交叉引用时使用的并且具有选项(字段切换\h以超链接到内容;第二个是“标准”超链接,您可以使用 Insert/Hyperlink 命令创建这样的超链接然后检查 Word 如何进行定位。
标签: python ms-word documentation python-docx