22
33from python_docx_replace .exceptions import EndTagNotFound , InitialTagNotFound , TableIndexNotFound
44from python_docx_replace .paragraph import Paragraph
5+ from docx .opc .constants import RELATIONSHIP_TYPE
6+
57
68__all__ = ["docx_replace" , "docx_blocks" , "docx_remove_table" ]
79
@@ -26,6 +28,7 @@ def docx_replace(doc, **kwargs: str) -> None:
2628 for p in Paragraph .get_all (doc ):
2729 paragraph = Paragraph (p )
2830 paragraph .replace_key (key , str (value ))
31+ _replace_in_links (doc , key , str (value ))
2932
3033
3134def docx_blocks (doc : Any , ** kwargs : bool ) -> None :
@@ -145,3 +148,18 @@ def _search_for_lost_end_tag(doc: Any, initial: str, end: str) -> None:
145148 paragraph = Paragraph (p )
146149 if paragraph .contains (end ):
147150 raise InitialTagNotFound (initial , end )
151+
152+ def _replace_in_links (doc : Any , key : str , value : str ):
153+ # Make replacements in hyperlink targets
154+ rel_dicts = []
155+ rel_dicts .append (doc .part .rels )
156+
157+ for section in doc .sections :
158+ rel_dicts .append (section .header .part .rels )
159+ rel_dicts .append (section .footer .part .rels )
160+
161+ for rels in rel_dicts :
162+ for rel_id , rel in rels .items ():
163+ if rel .reltype == RELATIONSHIP_TYPE .HYPERLINK :
164+ if key in rel ._target :
165+ rel ._target = rel ._target .replace (key , value )
0 commit comments