Skip to content

How to change style of hyperlinks in existing document? #1066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
a-peace opened this issue Mar 13, 2022 · 1 comment
Closed

How to change style of hyperlinks in existing document? #1066

a-peace opened this issue Mar 13, 2022 · 1 comment

Comments

@a-peace
Copy link

a-peace commented Mar 13, 2022

Especially font size and name, maybe even for all content in document.

Currently i'm using this snippet for changing style in document, but links are no affected. Should I recreate them?

from docx import Document
from docx.shared import Pt

document = Document("existing file.docx")

for paragraph in document.paragraphs:
    # paragraph.style = document.styles['Normal']
    for run in paragraph.runs:
        run.font.name = 'Arial'
        run.font.size = Pt(10)
@a-peace
Copy link
Author

a-peace commented Mar 17, 2022

from docx.oxml.shared import qn

This function is copy-paste from here. Because paragraph.runs is not returning Run instances for hyperlinks childrens.

def getParagraphRuns(paragraph):
    def _get(node, parent):
        for child in node:
            if child.tag == qn('w:r'):
                yield Run(child, parent)
            if child.tag == qn('w:hyperlink'):
                yield from _get(child, parent)
    return list(_get(paragraph._element, paragraph))

If you want to get sequence of Run instances only for hyperlinks use this function instead.

def getHyperlinksRuns(paragraph):
    def _get(node, parent):
        for child in node:
            if child.tag == qn('w:hyperlink'):
                yield from returnRun(child, parent)
    def returnRun(node, parent):
        for child in node:
            if child.tag == qn('w:r'):
                yield Run(child, parent)
    return list(_get(paragraph._element, paragraph))

and voila

for p in document.paragraphs:
    runs = getParagraphRuns(p) 
    # runs = getHyperlinksRuns(p)
    for run in runs:
        run.font.name = 'Arial'
        run.font.size = Pt(10)

@a-peace a-peace closed this as completed Mar 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant