Python-docx动态添加超链接

时间:2019-01-29 12:11:38

标签: python-docx

这是我的第一个要求。我是一名律师,我正在寻找一种可靠的方式来在文档中动态插入超链接。

我已经阅读了以前的文章的答案,但没有找到解决问题的方法。

那是我的问题:

  • 我有一个附带文件的文件夹,该文件应遵循明确的格式(即01_act.pdf; 02_contract.pdf; 03_invoice.pdf等;
  • 我有一个文档,在该文档中,我应该向特定的事件添加指向所需文档的超链接:(例如,我应将01_act.pdf的超链接附加到事件“ doc.1”,而02_contract.pdf的超链接到doc.2”等;

我已经意识到已经发布到此repository

的软件

如果我将出现的“ doc.1”标记为粗体和下划线,我看到在文档中创建了新的运行,并且系统似乎正常工作,但是有一些奇怪的行为。

例如,如果我有 1 ,我叫Roberto(文档1 ),则该软件可以识别运行并正确添加超链接(并且可以正常运行!),但是输出结果却很奇怪: 1 **** doc.1 。我叫Roberto()。

这是循环所有段落的代码:

# scansione dell'atto e aggiunta degli hyperlinks
for p in atto.paragraphs:
    for run in p.runs:
        for link in linksArray:
            found_link = link.__eq__(run.text)
            if(found_link):
                hyperlink.add(p, run, found_link)

# informo che la scansione è completata
print('Scansione completata\n Salvataggio in corso..')

atto.save(path.join(pathDir,'new-atto.docx'))

这是用于向运行中添加超链接的功能(我从其他答案中得出):

import docx

def add(paragraph, run, url):
    runs = paragraph.runs
    for i in range(len(runs)):
        if runs[i].text == run.text:
            break

    # 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, )
    hyperlink.append(run._r)
    paragraph._p.insert(i+1,hyperlink)

对于任何错误,我们都非常抱歉,但是我不是专业开发人员,只是一个对编码充满热情的律师:-)

0 个答案:

没有答案