python-openxml / python-docx

Create and modify Word documents with Python
MIT License
4.54k stars 1.11k forks source link

"FollowedHyperlink" cannot be found in some documents even though it is present in all. #1376

Open DanyaalMajid opened 5 months ago

DanyaalMajid commented 5 months ago

I have been facing this peculiar issue, i need to change the color of the FollowedHyperlink style to something else, but it cant be found in some documents, even though all the documents were created by python-docx from the start.

If i try to manually create the style if its not found, it shows up as "FollowedHyperlink1" and does not change the color of the "Followed Hyperlink".

The code i have been using is below:

    dest_doc = Document(dest_file)
    dest_doc.styles["Normal"].font.name = "Arial"
    dest_doc.styles["Normal"].font.size = Pt(11)
    dest_doc.styles["Normal"].paragraph_format.line_spacing = 1
    dest_doc.styles["Normal"].paragraph_format.space_after = Pt(0)
    dest_doc.styles["Normal"].paragraph_format.space_before = Pt(0)
    dest_doc.styles["List Bullet 3"].paragraph_format.line_spacing = 1
    dest_doc.styles["Hyperlink"].font.color.rgb = RGBColor(20, 57, 111)

    # Get the existing Followed Hyperlink style
    followed_hyperlink_style = None
    for style in dest_doc.styles:
        if style.name == "FollowedHyperlink" or style.name == "Followed Hyperlink":
            followed_hyperlink_style = style
            break

    # Check if Followed Hyperlink style exists
    if followed_hyperlink_style:
        # Set color for followed hyperlinks
        followed_hyperlink_style.font.color.rgb = RGBColor(20, 57, 111)
        print("Color Applied")
    else:
        with open("missing_fh.txt", "a") as file:
            file.write(dest_file + "\n")
        print("Followed Hyperlink style not found.")

Please help fix this, all documents being processed were created from scratch by python-docx. Also the FollowedHyperlink style in the unmodified docx is actually called "Followed Hyperlink (Hide Until Used)", but its the same case in even the documents for which the style is found, so i dont think the Hide Until Used thing is an issue.

TalibRazaa commented 5 months ago

Hi, This might help you

from docx import Document from docx.enum.style import WD_STYLE_TYPE

dest_doc = Document(dest_file)

... (other style modifications)

Get or create the Followed Hyperlink style

followed_hyperlink_style = None for style in dest_doc.styles: if style.name.lower() == "followedhyperlink": followed_hyperlink_style = style break

if not followed_hyperlink_style: print("Creating Followed Hyperlink style...") followed_hyperlink_style = dest_doc.styles.add_style( "FollowedHyperlink", WD_STYLE_TYPE.CHARACTER )

Set color for followed hyperlinks

followed_hyperlink_style.font.color.rgb = RGBColor(20, 57, 111)