Skip to content Skip to sidebar Skip to footer

How To Add W:altchunk And Its Relationship With Python-docx

I have a use case that make use of element in Word document by inject (fragment of) HTML file as alternate chunks and let Word do it works when the file gets op

Solution 1:

Well, some hints here anyway. Maybe you can post your working code at the end as a full "answer":

  1. The alt-chunk part needs to start its life as a docx.opc.part.Part object.

    The blob argument should be the bytes of the file, which is often but not always plain text. It must be bytes though, not unicode (characters), so any encoding has to happen before calling Part().

    I expect you can work out the other arguments:

    • package is the overall OPC package, available on document.part.package.
    • You can use docx.opc.package.OpcPackage.next_partname() to get an available partname based on a root template like: "altChunk%s" for a name like "altChunk3". Check what partname prefix Word uses for these, possibly with unzip -l has-an-alt-chunk.docx; should be easy to spot.
    • The content-type is one in docx.opc.constants.CONTENT_TYPE. Check the [Content_Types].xml part in a .docx file that has an altChunk to see what they use.
  2. Once formed, the document_part.relate_to() method will create the proper relationship. If there is more than one relationship (not common) then you need to create each one separately. There would only be one relationship from a particular part, just some parts are related to more than one other part. Check the relationships in an existing .docx to see, but pretty good guess it's only the one in this case.

So your code would look something like:

package = document.part.package
partname = package.next_partname("altChunkySomethingPrefix")
content_type = docx.opc.constants.CONTENT_TYPE.THE_RIGHT_MIME_TYPE
blob = make_the_altChunk_file_bytes()

alt_chunk_part = Part(partname, content_type, blob, package)

rId = document.part.relate_to(alt_chunk_part, RT.A_F_CHUNK)
etc.

Post a Comment for "How To Add W:altchunk And Its Relationship With Python-docx"