добавление гиперссылки к тексту в абзаце (libreoffice, Google Docs) - PullRequest
0 голосов
/ 31 марта 2020

Я запускаю Ubuntu 19, я попробовал несколько примеров из # 74 Github и При добавлении гиперссылки в MSWord с помощью python -docx гиперссылка не работает; в libreoffice или даже в Google Docs есть ли способ заставить его работать в Google Docs и LibreOffice?

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 site', "https://www.google.com")
p.add_run('hello this is after link')
document.save('demo_hyperlink.docx')

1 Ответ

1 голос
/ 01 апреля 2020

Для управления Документом Google необходимо использовать API Документов Google .

К сожалению, python -docx не может управлять Документом Google , Потому что он не может использовать Docs API. Поэтому здесь я хотел бы предложить использовать googleapis для python.

. Пример сценария можно посмотреть на официальном документе .

Ссылки:

...