1717from lxml import etree
1818
1919
20+ W14_ANCHOR_ID = (
21+ "{http://schemas.microsoft.com/office/word/2010/wordml}anchorId"
22+ )
23+
24+
2025class SubdocComposer (Composer ):
2126 def attach_parts (self , doc , remove_property_fields = True ):
2227 """Attach docx parts instead of appending the whole document
@@ -30,6 +35,7 @@ def attach_parts(self, doc, remove_property_fields=True):
3035 cprops .dissolve_fields (name )
3136
3237 self ._create_style_id_mapping (doc )
38+ self .renumber_ole_objects (doc )
3339
3440 for element in doc .element .body :
3541 if isinstance (element , CT_SectPr ):
@@ -50,6 +56,71 @@ def attach_parts(self, doc, remove_property_fields=True):
5056 self .renumber_nvpicpr_ids ()
5157 self .fix_section_types (doc )
5258
59+ def renumber_ole_objects (self , doc ):
60+ state = getattr (self .doc .part , "_docform_ole_id_state" , None )
61+ if state is None :
62+ body = self .doc .element .body
63+ state = {
64+ "shape_ids" : set (xpath (body , ".//v:shape/@id" )),
65+ "shape_index" : 1025 ,
66+ "object_ids" : set (xpath (body , ".//o:OLEObject/@ObjectID" )),
67+ "object_index" : 1 ,
68+ "anchor_ids" : {
69+ element .get (W14_ANCHOR_ID ).upper ()
70+ for element in body .iter ()
71+ if element .get (W14_ANCHOR_ID ) is not None
72+ },
73+ "anchor_index" : 1 ,
74+ }
75+ self .doc .part ._docform_ole_id_state = state
76+
77+ state ["shape_ids" ].update (
78+ xpath (doc .element .body , ".//v:shape/@id" )
79+ )
80+ for ole_object in xpath (doc .element .body , ".//o:OLEObject" ):
81+ old_shape_id = ole_object .get ("ShapeID" )
82+ matching_shapes = [
83+ shape
84+ for shape in xpath (ole_object .getparent (), "./v:shape" )
85+ if (
86+ old_shape_id is not None
87+ and shape .get ("id" ) == old_shape_id
88+ )
89+ ]
90+ if len (matching_shapes ) == 1 :
91+ shape_id = self ._next_ole_id (
92+ state , "shape" , lambda index : "_x0000_i%d" % index
93+ )
94+ matching_shapes [0 ].set ("id" , shape_id )
95+ ole_object .set ("ShapeID" , shape_id )
96+ if ole_object .get ("ObjectID" ) is not None :
97+ ole_object .set (
98+ "ObjectID" ,
99+ self ._next_ole_id (
100+ state , "object" , lambda index : "_%d" % index
101+ ),
102+ )
103+
104+ for element in doc .element .body .iter ():
105+ if element .get (W14_ANCHOR_ID ) is not None :
106+ element .set (
107+ W14_ANCHOR_ID ,
108+ self ._next_ole_id (
109+ state , "anchor" , lambda index : "%08X" % index
110+ ),
111+ )
112+
113+ @staticmethod
114+ def _next_ole_id (state , kind , formatter ):
115+ index_key = "%s_index" % kind
116+ ids_key = "%s_ids" % kind
117+ while formatter (state [index_key ]) in state [ids_key ]:
118+ state [index_key ] += 1
119+ value = formatter (state [index_key ])
120+ state [index_key ] += 1
121+ state [ids_key ].add (value )
122+ return value
123+
53124 def add_diagrams (self , doc , element ):
54125 # While waiting docxcompose 1.3.3
55126 dgm_rels = xpath (element , ".//dgm:relIds[@r:dm]" )
0 commit comments